Python基礎練習-組織文件

前言:
需求:將(MM-DD-YYYYY)改成(DD-MM-YYYY)

項目:

  • 檢查當前工作目錄的所有文件名,尋找美國風格的日期
  • 如果找到,將改文件改名,交換月份和日期的位置,使之成爲歐洲風格

具體實現:

  • 創建一個正則表達式,可以識別到沒過風格日期的文本模式
  • 調用os.listdir(),找出工作目錄中的所有文件
  • 循環遍歷每隔文件名,湧shutil.move()對改文件改名
#! python3
# renameDates.py - Renames filenames with American MM-DD-YYYY date format
# to European DD-MM-YYYY.

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 the month
    ((0|1|2|3)?\d)- # one or two digits for the day
    ((19|20)\d\d) # four digits for the year (must start with 19 or 20)
    (.*?)$ # 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 files without a date.
    if mo == None:
        continue

    # Get the different parts of the filename.
    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 paths.
    absWorkingDir = os.path.abspath('.')
    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) # uncomment after testing

 

擴展:

  • 爲文件名添加前綴,諸如添加test_,將eggs.txt改成test_eggs.txt
  • 更改日期風格
  • 刪除文件名中的0,如asd001.txt
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章