python batch change filename in order
In the previous batch modification of the file name of the problem is the use of the appearance of disorder, that is, the modification of the file name is not in accordance with the order of the file arrangement, resulting in unnecessary trouble.
The order of arrangement is in the order of e.g.: 1, 10, 11, 2, 20, 21... The normal order you want to achieve: 1, 2, 3, 4, 5...
solution code
import os # Set the file path path='C:/Users/Louise Meow/Desktop/FOV60/' # Get all the files in the directory and put them in the list fileList=(path) #get_key is the element used by the sorted function to compare, where the function is replaced by a lambda expression. get_key = lambda i : int(('.')[0]) new_sort = sorted(fileList, key=get_key) #print(fileList, '\n', new_sort) n = 0 for i in fileList: # Set old filename (that's path + filename) oldname = path + + new_sort[n] # Add system separator # Set new file name newname = path + + 'p' + str(n + 1)+'.csv' (oldname, newname) # Rename a file using the rename method in the os module. print(oldname, ' ======> ', newname) n += 1
where the key statement for sorting is:
get_key = lambda i : int(('.')[0]) new_sort = sorted(fileList, key=get_key)
split() is a commonly used method of separating characters, split('.') [0] means to . to separate the contents in front of . The content in front of the .
Run results:
python batch incremental filename modification code in order (can specify filename)
If you need to add other corresponding characters in the file name, modify the corresponding character part of the code can be, this method is relatively simple, easy to understand.
import os # Set the path to the folder to be renamed folder_path = 'C:/Users/Administrator/Desktop/CR/RGB Three Channel' # Get the names of all files in the folder file_names = (folder_path) # Set the starting number start_num = 1 # Iterate over the list of filenames and change the filename for file_name in file_names: # Get the filename suffix file_extension = (file_name)[1] # Construct new filenames new_file_name = str(start_num) + file_extension #You can also rename files differently by adding the appropriate characters here #new_file_name = "corresponding character" + str(start_num) + file_extension # Construct the path to the old file and the path to the new file old_file_path = (folder_path, file_name) new_file_path = (folder_path, new_file_name) # Rename files (old_file_path, new_file_path) print(f'{file_name}has been renamed{new_file_name}') # Incremental numbering start_num += 1
summarize
The above is a personal experience, I hope it can give you a reference, and I hope you can support me more.