Python retrieves all txt files in a directory and changes the file to. log

Source: Internet
Author: User

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.