Python implements batch Object Name modification for instances,

Source: Internet
Author: User

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.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.