利用python對多個txt檔案中的資料進行篩選
阿新 • • 發佈:2019-02-09
一、問題描述
篩選出多個txt檔案中需要的資料
二、資料準備
這是我自己建立的要處理的檔案,裡面是隨意寫的一些數字和字母
三、程式編寫
import os
def eachFile(filepath):
pathDir =os.listdir(filepath) #遍歷資料夾中的text
return pathDir
def readfile(name):
fopen=open(name,'r')
for lines in fopen.readlines(): #按行讀取text中的內容
lines = lines.replace("\n", "").split(",")
if 'aaa' in str(lines) and '2' not in str(lines):
#篩選出含有'aaa'並且不含數字2的每一行
print(lines)
fopen.close()
filePath = "C:\\Users\\Administrator\\Desktop\\123"
pathDir=eachFile(filePath)
for allDir in pathDir:
# child = os.path.join('%s%s' % (filepath, allDir))
child = "C:\\Users\\Administrator\\Desktop\\123" + '\\' + allDir
readfile(child)
以上只是利用if條件句對資料進行簡單的篩選,可以用正則表示式做更復雜的資料篩選。