Python implements batch Object Name modification for instances,
This example describes how to modify file names in batches in Python. Share it with you for your reference. The details are as follows:
After downloading the comments "helong Legend", all the file names contain xxx audio downloads. Use the script to remove them. The script involves the OS. rename method, the str. partition method, and the regular match and search methods.
# Encoding: UTF-8 ### name of the file, for example, # helong legend \ dw.gov.cn-www.ysx8.com;## import OS, refs = OS. listdir ('shan tianfang _ he long legend ') for f in fs: ###### Method 1: partition gets useless characters #1. divide the file name into three parts with the '[' character # ls = f. partition ('[') # 2.ls[ 0] is the required file name. Therefore, obtain ls [1:] # dirtystring = ''. join (ls [1:]) #3. start to replace # newname = f. replace (dirtystring, '') + 'shanghai') # OS. rename ('Dan tianfang _ he long legend/'+ f, newname) ##### Method 2: obtain useless characters dirtymatch = re using regular expressions. search (R '\[. *? \] ', F) if dirtymatch: dirtystring = dirtymatch. group (0) newname = f. replace (dirtystring, '') + 'replace 'OS. rename ('shan tianfang _ he long legend/'+ f, newname) # Note: You can directly use re. use the sub method to replace the regular expression with no characters in the file name.
I hope this article will help you with Python programming.