#! python3
import shutil,os,re
# 创建一个正则表达式,它可以匹配文件的美国日期。
dataPattern = re.compile(r"""^(.*)?
(0|1)?\d")- #匹配月
(0|1|2|3)?\d)- #匹配日
(19|20)\d\d) #匹配年
(.*?)$ #日期后的所有文本
""",re.VERBOSE)
# to loop over the files in the working directory.
for amerFilename in os.listdir('.'):
mo = dataPattern.search(amerFilename)
if mo == None: # 跳过没有日期的文件
continue
beforePart = mo.group(1) #得到文件的名称
monthPart = mo.group(2)
dayPart = mo.group(4)
yearPart = mo.group(6)
afterPart = mo.group(8)
dataPattern = re.compile(r"""^(1) # all text before the data
(2 (3) )- # one or two digitals for the month
(4 (5) )- # one or two digitals for day
(6 (7) ) # four digitals for year
(8)$ # all text after the date
""",re.VERBOSE)
# 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 "%s" to "%s"...' %(amerFilename,euroFilename))
#shutil.move(amerFile,euroFilename)
# uncomment after testing
os.listdir('.')
返回当前目录的所有文件
beforePart表示你文件名的前缀,你的文件名由前缀加上日月年加上后缀组成