Renaming a batch Python script

Source: Internet
Author: User
The copy of ********.bmp or copy of copy of ********.bmp such files are uniformly named ********0.bmp or ********00.bmp format, and the number of the following 0 represents ********. The number of BMP occurrences +1. Wrote a small script below:

The code is as follows:


Import OS
"""
This program is used to rename the file name because there are many copy of the file name in the folder, so remove Windows
Rename style and replace with new additive naming mechanism
Author: chenxofHit@gmail.com
Date: April 13, 2011
"""
def getfilenames (dirs, dict):
#dir为目录名, LST list
Filenames=os.listdir (dirs)
For name in filenames:
Key = Filenames[filenames.index (name)]
Sign = "Copy of"
Judge = Key.find (sign)
if (Judge! =-1):
Dict[key] = 1
else: #提取其中的真实文件名
truekey= key[-12:] #因为真实的文件名都是在12位
If Truekey not in Dict: #字典中不存在
Dict[truekey]=1
Os.rename (Dirs+str (OS.SEP) +name,dirs+str (OS.SEP) +truekey)
Else
#split Finames
newkey= str (truekey[:-4]) +str (' 0 ' *dict[truekey]) + str (truekey[-3:])
Dict[truekey] = dict[truekey]+1
Os.rename (Dirs+os.sep+name,dirs+os.sep+newkey)

If ' __name__=__main__ ':
dict={}
dirs = "C://temp"
GetFileNames (dirs, Dict)


Use of the dictionary, the use of the OS module, learned something, hehe!
  • 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.