preamble
When we crawl a number of images from a website, or need to modify some txt, excel, jpg, and other large batch files into regular names for easy organization.
Tip: Below is the body of this post, with the following examples for reference
First, python batch modify file name
Tip: The folder to be modified can only contain files that need to be modified, then change the path inside the source code.
1. Source Code
The code is as follows (example):
# Batch change file name #Batch change image file names import os import re import sys def renameall(): fileList = (r"E:\py\python3.7\test\test17") # Folders to be modified print("Before modification:"+str(fileList)) # Files contained in the output folder currentpath = () # Get the current working directory of the process (r"E:\py\python3.7\test\test17") # Change the current working directory to the location of the folder to be modified num=1 # Name variables for fileName in fileList: # Iterate over all files in a folder pat=".+\.(jpg|png|gif|py|txt)" # Match filename regular expression pattern = (pat,fileName) # Make a match (fileName,(str(num)+'.'+pattern[0])) # File renaming num = num+1 #Change the number and continue to the next item print("---------------------------------------------------") (currentpath) # Change back to the working directory before the program was run () #Refresh print("Modified:"+str((r"E:\py\python3.7\test\test17"))) # Output the files contained in the modified folder renameall()
Second, python batch modify the file name (in order)
1. Source Code
Tip: the use of the appearance of disorder, that is, when modifying the file name is not in accordance with the order in which the files are arranged, such as the arrangement of the order is in accordance with, for example: 1, 10, 11, 2, 20, 21 ... the order of the normal order you want to get: 1, 2, 3, 4, 5 ... the need to be sorted (reference from thehttps:///article/)
The code is as follows (example):
import os # Set the file path path=r'E:\py\python3.7\test\test19\excel' # Get all the files in the directory and put them in the list fileList=(path) The #get_key is the element used by the sotred 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
Third, python batch modify the file name (delete the specified characters)
1. Batch delete the specified character segment "- Summary Data - 20211123".
2, batch delete the specified character segment "[ * Turing Programming Series * ]."
(Reference from /qiukui111)
1. Source Code
The code is as follows (example):
import os import re import time """Selectively change the names of all files in a given directory""" def ReFileName(dirPath,pattern): """ :param dirPath: folder path :param pattern: regular pattern :return. """ # Iterate over the files in the directory for file in (dirPath): # Determine if it's a file if ((dirPath, file)) == True: # Remove unwanted words by regular matching newName = (pattern, "", file) # Set new file name newFilename = (file, newName) # Rename ((dirPath, file), (dirPath, newFilename)) print("The file name has been harmonized successfully.") if __name__ == '__main__': timeStart = () dirPath = r"E:\py\python3.7\test\test19\excel1" # pattern = (r'\[{1}(.+)]\.') pattern = (r'\-class{1}(.+)3') ReFileName(dirPath,pattern) timeEnd = () print("Program gone %d seconds."%(timeEnd-timeStart))
Fourth, python batch modify the file name (according to excel given format)
1, batch according to excel name and student number matching modify picture name;
1. Source Code
The code is as follows (example):
import os import xlwings as wx def listdir(path, list_name): # Pass in the stored list for file in (path): # Exclude temporary documents if '~$' in file: continue # Obtain a list of photographs if ".jpg" in file: file_path = (path,file) list_name.append(file_path) # Get the excel file if ".xlsx" in file: index_file = (path,file) print("Data Source Files - >"+index_file) print(list_name) return index_file def getinfo(new_name,index_file): # Obtain the name and number of the person app = (visible=False, add_book=False) # Not opening baiexcel print("Reading personnel information-->"+index_file) wb = (index_file) sheet = [0] nrows = sheet.used_range.last_cell.row # Get the maximum number of rows ncolumns = sheet.used_range.last_cell.column # Get the maximum number of columns # Find columns for names and numbers file_name = "" empl_name = "" empl_numb = "" ename_col = 0 enumb_col = 0 print("Maximum number of columns - >"+str(ncolumns)) for col in range(1, ncolumns+1): if ((1,col)).value == "Name": ename_col = col print("Columns for names-->"+str(col)) if ((1,col)).value == "School number.": enumb_col = col print("Columns for Employee Number-->"+str(col)) # Take the name and number from the line for row in range(2,nrows+1): empl_name = str(((row,ename_col)).value) empl_numb = str(((row,enumb_col)).value) file_name = (empl_name + empl_numb).split('.')[0] # New name print(file_name) new_name.append(file_name) print(new_name) () () def change_name(file_path,new_name,list_name): # Processing photos one by one for filename in list_name: print("Old file name"+filename) old_name = ((filename)).split('.')[0] # Find out if this name is in the list of new names for nfile in new_name: if old_name in nfile: nfname = file_path++nfile+".jpg" print("New filename"+nfname) (filename,nfname) break def main(): file_path = input('Enter folder path:') # Folder location try: # Read all files in a folder List_files=[] index_file = listdir(file_path,List_files) # Read the employee name and employee number to form a new filename new_name=[] getinfo(new_name,index_file) # Change the name of the file change_name(file_path,new_name,List_files) except Exception as e: # Print exception messages print(e) if __name__ == '__main__': main()
summarize
to this article on python batch file name change the three methods of the article is introduced to this, more related python batch file name change content please search for my previous articles or continue to browse the following related articles I hope you will support me more in the future!