出于在一些日常工作中需要用到的一些工具记录,可以节省大量时间。
替换文件夹下所有文件中的空格
# -*- encoding=utf-8 -*-
import os
absolute_path=r"D:\Documents"
def remove_path_file_empty_space(path,is_loop=False):
dir_list=os.listdir(path)
for item in dir_list:
abs_path=path+"\\"+item
if os.path.isdir(abs_path):
if is_loop:
remove_path_file_empty_space(path,is_loop)
if " " in item:
new_path=path+"\\"+item.replace(" ","_")
os.rename(abs_path,new_path)
elif os.path.isfile(abs_path):
if " " in item:
new_path=path+"\\"+item.replace(" ","_")
os.rename(abs_path,new_path)
if __name__ == "__main__":
remove_path_file_empty_space(absolute_path,True)
查找文件夹下所有特定后缀文件中的关键词汇并输入到指定文件中
# -*- encoding=utf-8 -*-
import os
import re
from pip._vendor import chardet
output_path=r"D:\Documents\OutputDir\Result.txt"
absolute_path=r"D:\Documents\TargetDir"
def find_keyword_in_files_at_dir(path,suffix,is_loop=False):
dir_list=os.listdir(path)
for item in dir_list:
abs_path=path+"\\"+item
if os.path.isdir(abs_path):
if is_loop:
find_keyword_in_files_at_dir(path,suffix,is_loop)
elif os.path.isfile(abs_path):
#取文件后缀
ext_str=item.split(".")[-1]
if ext_str==suffix:
#取文件编码
encoding_str="utf-8"
with open(abs_path,"rb") as f:
data=f.read()
encoding_str=chardet.detect(data)["encoding"]
f.close()
with open(abs_path,"r",encoding=encoding_str) as f:
lines=f.readlines()
cur_line=1
for line in lines:
line=str(line)
if re.match(pattern,line):
with open(output_path,"a",encoding="utf-8") as f1:
write_str="文件:"+abs_path+": "+line.replace("\n","")+" "+str(cur_line)+"行\n"
f1.write(write_str)
f1.close()
cur_line+=1
f.close()
if __name__ == "__main__":
pattern=re.compile(" *(HelloWorld).*")
find_keyword_in_files_at_dir(absolute_path,"txt",True)
思路:1.通过绝对路径读取到文件夹下的所有文件和子文件夹,如果需要遍历所有子文件夹,则采用递归实现。然后就是对每个文件进行处理,包括对文件重命名,读取文件内容,然后再通过正则表达式去按行进行匹配。
2.其中有个小细节是如何取得当前文件的编码。如果读取文件编码不正确会导致出错。
对于系统相关的操作可以仔细去阅读python的os模块以及os下的path。
注:出于环境原因,以上代码都是无提示手打,如有错误,还请指正