004.文件更名

#pythonn3
#renameDatet.py -rename filesnames with American MM-DD-YYYY date format
#to European DD-MM-YYYY
#shutil.move()可以用于文件改名.正则表达式中,每遇到一个左括号group就累计加1
import  shutil,os,re
#create a regex that matches files with the american date format.
datepattern = re.compile(r'''^(.*?)       #all text before the date
                        ((0|1)?\d)-   #one or two digits for month 
                        ((0|1|2|3)?\d)- #one or two digits for the  day
                        ((19|20)\d\d)   #four digits for the year
                        (.*?)$          #all text after the date
                        ''',re.VERBOSE)
#todo:loop over the files in the working directory.
path = 'E:\\04.AutomationProject\\PracticePython\\noteBasic'
for amerFileName in os.listdir(path):
    mo = datepattern.search(amerFileName)
#todo:Skip files without a date.
    if mo == None:
        continue
#todo:get the different parts of the filenames
    beforePart = mo.group(1)
    monthPart = mo.group(2)
    dayPart = mo.group(4)
    yearPart = mo.group(6)
    afterPart = mo.group(8)
    #form the European-style filename
    euroFileName = beforePart + yearPart + '-' + monthPart + '-' + dayPart + afterPart
    #get the full,absolute file path
    absWorkingDir = os.path.abspath(path)
    amerFileName = os.path.join(absWorkingDir,amerFileName)
    euroFileName = os.path.join(absWorkingDir,euroFileName)
    #rename the files.
    # print('Renaming "%s" to "%s"...'%(amerFileName,euroFileName))
    shutil.move(amerFileName,euroFileName) #document after testinng

猜你喜欢

转载自blog.csdn.net/baidu_27361307/article/details/80973037