目的:从多个文件中筛选包含某个字符串的文件
import os
from shutil import copy
# 获取所有后缀为.log 的文件
def getAllFiles(targetDir):
files = []
listFiles = os.listdir(targetDir)
for i in range(0, len(listFiles)):
path = os.path.join(targetDir, listFiles[i])
if os.path.isdir(path):
files.extend(getAllFiles(path))
elif os.path.isfile(path):
if path.endswith('.log'):
files.append(path)
return files
# 读取文件信息
def readfile(path):
lines = []
with open(path, 'r', encoding='utf-8') as readhost:
line = readhost.readlines()
for i in line:
l = i.replace("\n", "")
lines.append(l)
return line
# 筛选信息
def getresult(line):
fund_account = '53151363'
results = []
for i in line:
result = i.find(fund_account)
if result != -1:
results.append(i)
return results
# 筛选文件
def copyfile(src, target):
files = getAllFiles(src)
for i in files:
log_list = readfile(i)
rlt = getresult(log_list)
if rlt:
copy(i, target)
if __name__ == '__main__':
resource = r'E:\applog\1\trade-applog-F-20221101'
target = r"C:\Users\likf\Desktop\result2022\1"
copyfile(resource, target)
标签:files,文件,多个,搜索,__,path,line,os
From: https://www.cnblogs.com/likaifei/p/17054690.html