功能
查找当前目录下符合正则表达式的的文件的文本 将该文本写入到 新的文件夹
实现原理
- 按时间从小到大排序,遍历当前文件夹的文件
- 读取每个文件的内容
- 每行匹配到的文本信息 写入新文件
代码
import re
import os
import sys
# cmd执行 该文件
# FindMessage.py
parttern = "正则表达式" # 配置正则表达式
newFile = "newFiles.txt" # 匹配的字符串写入的文件
def read_file(filePath,writeFile):
with open(filePath,"r",errors='ignore') as file:
lines = file.readlines()
for line in lines:
result = re.search(parttern,line,re.I)
if result == None:
continue
writeFile.write(line)
file.close()
def check_files():
with open(newFile, "w", errors='ignore') as writeFile:
for root, dirs, files in os.walk("./"):
files = sorted(files, key=lambda x: os.path.getmtime(os.path.join("./", x))) # 按时间从小到大排序
print(files)
for file in files:
print("checking file: "+file);
if file == newFile || file == "FindMessage.py":
continue
writeFile.write("\n========"+file+"========\n")
read_file(os.path.join("./", file),writeFile);
writeFile.close()
if __name__=="__main__":
check_files()