Batch modification of file names (retaining suffixes)
With this method, the original suffix of the file is preserved. The main demonstration here is the modification of the image name.
# Batch modification of file names # Batch change image file names import os import re import sys path = 'F:\Temp\ZZ' fileList = (path) # Folders to be modified print("Before modification:"+str(fileList)) # Files contained in the output folder currentpath = () # Get the current working directory of the process (path) # Change the current working directory to the location of the folder to be modified n = 1 # Name variables for fileName in fileList: # Iterate over all files in a folder pat=".+\.(jpg|png|jpeg)" # Match filename regular expression pattern = (pat,fileName) # Make a match (fileName,(str(n)+'.'+pattern[0])) # File renaming n += 1 # Change the number and continue to the next item (currentpath) # Change back to the working directory before the program was run () # Refresh print("Modified:"+str((path))) # Output the files contained in the modified folder
Batch modification of file names (full change)
This method, modifies the original suffix of the file. The main demonstration here is the modification of the image.
import os path = 'F:\Temp\ZZ' # Get all the files in the directory and put them in a list fileList = (path) n = 0 for i in fileList: # Set old filename (that's path + filename) oldname = path + + fileList[n] # Add system separator # Set new file name newname = path + + 'a' + str(n+1) + '.jpg' (oldname, newname) # Rename a file using the rename method in the os module. print(oldname, '======>', newname) n += 1
There is a small caveat to the code. For example, if the file name was originally something like , , then running the above code would result in an error. Just change the letter a to something else. This is because there is a file with that name in the folder, and when the program changes the name, two files with the same name will co-exist during the run.
Read all filenames under the file
import os # Output all folder names and file names path = 'F:\Temp\ZZ' dataFileList = (path) for i in dataFileList: print(i) # Read a specific filename txtFile = [] for filename in dataFileList: j = ('.') if len(j)==2: if j[1]=='txt': (filename)
summarize
To this article on Python batch file name changes to this article, more related to Python batch file name changes to the content please search my previous articles or continue to browse the following related articles I hope you will support me in the future more!