在處理數據的時候,因為沒有及時的去重,所以需要重新對生成txt進行去重。
可是一個文件夾下有很多txt,總不可能一個一個去操作,這樣效率太低了。這里我們需要用到 os 這個包
關鍵的代碼
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
|
<span style = "font-size:14px;" > # coding=utf-8 #出現了中文亂碼的問題,于是我無腦utf-8 。希望后期的學習可以能理解 import os import os.path import re import sys import codecs reload (sys) sys.setdefaultencoding( 'utf-8' ) #這里放著你要操作的文件夾名稱 path = 'E:\\get_key\\' #把e:\get_key\目錄下的文件名全部獲取保存在files中 files = os.listdir(path.decode( 'utf-8' )) #用set可以很好的去重,在數據處理的時候經常會被使用到。這里做初始化 datas = set () for file in files : #準確獲取一個txt的位置,利用字符串的拼接 txt_path = 'E:\\get_key\\'+file.decode(' utf - 8 ') #把結果保存了在contents中 contents = codecs. open (txt_path.decode( 'utf-8' ), 'r' ,encoding = 'utf-8' ) #datas的數據清空 datas.clear() #把數據add到datas中,可以去重 for content in contents: print (content.decode( 'utf-8' )) datas.add(content.decode( 'utf-8' )) #去重后新的文件保存的路徑 new_txt_path = 'E:\\get_key3\\' + file.decode(' utf - 8 ') unique_keywords = codecs. open (new_txt_path.decode( 'utf-8' ), 'w' , encoding = 'utf-8' ) #把datas里的數據輸出到新生成的txt中 for data in datas: unique_keywords.write(data + "\n" ) #釋放資源 unique_keywords.close()< / span> |
以上這篇Python 讀取某個目錄下所有的文件實例就是小編分享給大家的全部內容了,希望能給大家一個參考,也希望大家多多支持服務器之家。
原文鏈接:https://blog.csdn.net/MakeContral/article/details/71544107