检索一个目录及子目录下所有的txt文件,并把txt文件后缀改为log:
import os f_path = r'C:UsersPycharmProjectsmystudyTestfolder' 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:UsersshenpingAppDataLocalProgramsPythonPython36-32python.exe C:/Users/PycharmProjects/mystudy/修改文件类型.py
找到文件C:UsersPycharmProjectsmystudyTestfolderf1f5f6 t.txt,已修改成:tt.log
找到文件C:UsersPycharmProjectsmystudyTestfolderf1f5gg.txt,已修改成:gg.log
找到文件C:UsersPycharmProjectsmystudyTestfolderf1fw1.txt,已修改成:fw1.log
找到文件C:UsersPycharmProjectsmystudyTestfolderf2fw2.txt,已修改成:fw2.log
找到文件C:UsersPycharmProjectsmystudyTestfolderf4fw4.txt,已修改成:fw4.log
找到文件C:UsersPycharmProjectsmystudyTestfolderw1.txt,已修改成:w1.log
找到文件C:UsersPycharmProjectsmystudyTestfolderw2.txt,已修改成:w2.log
找到文件C:UsersPycharmProjectsmystudyTestfolderw3.txt,已修改成:w3.log
找到文件C:UsersPycharmProjectsmystudyTestfolderw4.txt,已修改成:w4.log
已修改文件: ['tt.txt', 'gg.txt', 'fw1.txt', 'fw2.txt', 'fw4.txt', 'w1.txt', 'w2.txt', 'w3.txt', 'w4.txt']