Python implements bulk modification of file name instances

Source: Internet
Author: User
The examples in this article describe how Python implements bulk modification of file names. Share to everyone for your reference. Specific as follows:

Download the storytelling "He he legend", the file name contains xxx audio download, with a script to remove it. Scripts involve Os.rename renaming methods, Str.partition method use, and regular Match,search method differences

# encoding:utf-8### file name such as: # Helong legend \d+[www.ysx8.com].mp3# #import os,refs=os.listdir (' Shan Tianfang _ The legend ') for F in fs:  ##### #方法一: Partition gets  The #1 of the useless characters. The file name is divided into 3 parts  #ls =f.partition (' [')  #2. Ls[0] to require a file name, so get ls[1:]  # dirtystring = ". Join (ls[1:])  #3. Start replacing  #newname =f.replace (dirtystring, ') + '. mp3 ')  #os. Rename (' Shan Tianfang _ Long legend/' + F, newname)  ##### #方法二: Regular gets the useless characters  Dirtymatch = Re.search (R ' \[.*?\] ', f)  if Dirtymatch:    Dirtystring=dirtymatch.group (0)    newname=f.replace (dirtystring, ') + '. mp3 '    os.rename (' Shan Tianfang _ Helong Legend/' + F, newname)  #注意: can be directly replaced with the Re.sub method does not require characters in the file name

Hopefully 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.