python 检索一个目录下所有的txt文件,并把文件改为.log

时间:2023-03-08 16:36:05
python 检索一个目录下所有的txt文件,并把文件改为.log

检索一个目录及子目录下所有的txt文件,并把txt文件后缀改为log:

import os
f_path = r'C:\Users\PycharmProjects\mystudy\Testfolder'
def find_file(file_path, o_post, n_post, lis):
ls = os.listdir(file_path)
for i in ls:
son_path = os.path.join(file_path,i)
if os.path.isdir(son_path):
find_file(son_path,o_post,n_post,lis)
else:
file_post = str(i.split('.')[-1])
if file_post == o_post:
lis.append(i)
os.rename(son_path,str(son_path.split('.')[0])+'.'+n_post)
print('找到文件{srcnam},已修改成:{dicname}'.format(srcnam=son_path,dicname=str(i.split('.')[0])+'.'+n_post))
return lis
old_post = 'log'
new_post = 'txt'
print('已修改文件:',find_file(f_path, old_post, new_post, []))

运行结果:

C:\Users\shenping\AppData\Local\Programs\Python\Python36-32\python.exe C:/Users/PycharmProjects/mystudy/修改文件类型.py
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\f1\f5\f6\tt.txt,已修改成:tt.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\f1\f5\gg.txt,已修改成:gg.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\f1\fw1.txt,已修改成:fw1.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\f2\fw2.txt,已修改成:fw2.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\f4\fw4.txt,已修改成:fw4.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\w1.txt,已修改成:w1.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\w2.txt,已修改成:w2.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\w3.txt,已修改成:w3.log
找到文件C:\Users\PycharmProjects\mystudy\Testfolder\w4.txt,已修改成:w4.log
已修改文件: ['tt.txt', 'gg.txt', 'fw1.txt', 'fw2.txt', 'fw4.txt', 'w1.txt', 'w2.txt', 'w3.txt', 'w4.txt']