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
發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章