Retrieve all txt files in a directory and sub-directory and change the TXT file suffix to log:
ImportOsf_path= R'C:\Users\PycharmProjects\mystudy\Testfolder'deffind_file (File_path, O_post, N_post, lis): LS=Os.listdir (File_path) forIinchLs:son_path=Os.path.join (file_path,i)ifOs.path.isdir (Son_path): Find_file (Son_path,o_post,n_post,lis)Else: File_post= Str (I.split ('.') [-1]) ifFile_post = =o_post:lis.append (i) Os.rename (Son_path,str (Son_path.split ('.') [0]) +'.'+n_post)Print('file {Srcnam} found, modified to: {Dicname}'The. Format (SRCNAM=SON_PATH,DICNAME=STR (I.split ('.') [0]) +'.'+n_post)) returnLisold_post='Log'New_post='txt'Print('Modified file:', Find_file (F_path, Old_post, New_post, []))
Operation Result:
C:\Users\shenping\AppData\Local\Programs\Python\Python36-32\python.exe c:/users/pycharmprojects/mystudy/ Modify the file type. py
Found file C:\Users\PycharmProjects\mystudy\Testfolder\f1\f5\f6\tt.txt, modified to: Tt.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\f1\f5\gg.txt, modified to: Gg.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\f1\fw1.txt, modified to: Fw1.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\f2\fw2.txt, modified to: Fw2.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\f4\fw4.txt, modified to: Fw4.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\w1.txt, modified to: W1.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\w2.txt, modified to: W2.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\w3.txt, modified to: W3.log
Found file C:\Users\PycharmProjects\mystudy\Testfolder\w4.txt, modified to: W4.log
Modified files: [' Tt.txt ', ' gg.txt ', ' fw1.txt ', ' fw2.txt ', ' fw4.txt ', ' w1.txt ', ' w2.txt ', ' w3.txt ', ' w4.txt ']
Python retrieves all txt files in a directory and changes the file to. log