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 44 45 46 47 48 49
|
import os import re
dir ="/Library/work/workspace-my/test_file/file"
file_type=[".txt"]
look_up_table=[ ["第一行","aaaa"], ]
def get_filelist(dir,filetype): Filelist = [] for home, dirs, files in os.walk(dir): for filename in files: if(filename[-len(filetype):]==filetype): Filelist.append(os.path.join(home, filename)) return Filelist
if __name__ =="__main__": for type in file_type: print("开始处理"+type+"类型文件") file_list = get_filelist(dir,type) print("共发现"+str(len(file_list))+"个"+type+"类型文件") replace_count=0 file_count=0 for file in file_list: file_count=file_count+1 if(file_count%100==0): print("修改到第"+str(file_count)+"个文件") file_data="" with open(file, "r") as f: for line in f: for item in look_up_table: if re.search(item[0], line): line=re.sub(item[0],item[1],line) replace_count=replace_count+1 file_data += line with open(file,"w") as f: f.write(file_data) print("一共进行了"+str(replace_count)+"处替换") print("结束处理"+type+"类型文件") print("全部结束")
|