1. 程式人生 > >Python 讀取某個目錄下所有的檔案 -- untested

Python 讀取某個目錄下所有的檔案 -- untested

# coding=utf-8
#Python 讀取某個目錄下所有的檔案例項

import os
import os.path
import re
import sys
import codecs
reload(sys)
sys.setdefaultencoding('utf-8')
 

path = 'D:/mylinux/Git/mxnet-ssd/result'
 

files = os.listdir(path.decode('utf-8'))
 
#用set可以很好的去重
datas = set()
for file in files :
 txt_path = 'D:/mylinux/Git/mxnet-ssd/result/'+file.decode('utf-8')
 #把結果儲存了在contents中
 contents = codecs.open(txt_path.decode('utf-8'),'r',encoding='utf-8')
 datas.clear()
 #把資料add到datas中,可以去重
 for content in contents:
    print(content.decode('utf-8'))
    datas.add(content.decode('utf-8'))
 #去重後新的檔案儲存的路徑
 new_txt_path = 'D:/mylinux/Git/mxnet-ssd/result/' + 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()

From:https://www.jb51.net/article/142504.htm