Python Renaming Files with American-Style Dates to European-Style Dates

投稿者: | 2017年2月24日

アメリカ式の日付表記をヨーロッパ式の日付表記に変えるスクリプト

# !/user/bin/env python
# - Renames filenames with American MM-DD-YYYY date format
# to European DD-MM-YYYY

import shutil, os, re


def main():
    # Create a regex that matches files with American MM-DD-YYYY date format
    datePattern = re.compile(r"""
                    ^(.*?)          # all text before the date
                    ((0|1)?\d)-     # one or two digits for the 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)

    # loop over the files in the working directory
    for amerFilename in os.listdir('.'):
        mo = datePattern.search(amerFilename)

        # Skip file without date
        if mo == None:
            continue

        # Get different parts of the file name
        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 + daypart + '-' + monthPart + '-' + yearPart + afterPart

        #Get the full, absolute file path
        absWorkingDir = os.path.abspath(".")
        amerFilename = os.path.join(absWorkingDir, amerFilename)
        euroFilename = os.path.join(absWorkingDir, euroFilename)

        # Rename the files
        print('Renameing {} to {}'.format(amerFilename, euroFilename))
        shutil.move(amerFilename, euroFilename)





if __name__ == '__main__':
    main()

 

Pocket

コメントを残す

メールアドレスが公開されることはありません。 * が付いている欄は必須項目です

CAPTCHA