Get the App
SLTechnology News&Howtos  ›  Development  › 

How to modify file names in batches by Python

Shulou Source: shulou.com Published: 2022-05-31 23:45:14 10月03日 Update

This article mainly explains "Python how to modify the file name in batches", the content in the article is simple and clear, easy to learn and understand, the following please follow the editor's ideas slowly in depth, together to study and learn "Python how to modify the file name in batches"!

The original file name is as follows:

The effect of the modification is as follows:

Code:

Implement to copy each picture in the one folder to the two folder and modify the picture name to sort by a, b, c, d incrementally

Idea: rename to create a new file and copy the contents of the original file.

Import os def alterFileName (source,target): print ("there are the following files under the current folder >") file_list=os.listdir (source) print (file_list) os.mkdir (target) print (os.getcwd ()) # get the current directory os.chdir (source) # if the directory is not modified here To open the original file, you need to add the absolute path print (os.getcwd ()) ch='a' for file in file_list: name_list=file.rpartition ('.') # to the file name string according to'.' Slice t_name=target+'/'+ch+name_list [1] + name_list [2] print (t_name) f1=open (file,'rb') f2=open (t_name 'wb') while True: content=f1.read (1024) # read 1KB if content==b'': print once (f "{ord (ch)-96} picture copied >") ch=chr (ord (ch) + 1) f1.close () f2.close () Break f2.write (content) else: print (f "{len (file_list)} pictures have been copied to the {target} folder!") If _ _ name__ = ='_ main__': source_dir= "D:\\ PyProjects\\ one" # use\ or / can target_dir= "D:/PyProjects/two" alterFileName (source_dir,target_dir)

Running effect:

Thank you for your reading, the above is the content of "Python how to modify file names in batches". After the study of this article, I believe you have a deeper understanding of how Python modifies file names in batches, and the specific use needs to be verified in practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!

Tags: File file name picture folder content learning original idea effect directory under code character string namely situation article more knowledge Apple Docker Huawei Linux macOS MariaDB Microsoft MySQL NVidia OPPO Reno Shulou Tech Info Docker OPPO Reno Shulou Information Apple