标签:文件 group Python mo amerFilename euroFilename 日期 date os
随笔记录方便自己和同路人查阅。
#------------------------------------------------我是可耻的分割线-------------------------------------------
假定你的老板用电子邮件发给你上千个文件,文件名包含美国风格的日期(MM-DD-YYYY),需要将它们改名为欧洲风格的日期(DD-MM-YYYY)。手工 完
成这个无聊的任务可能需要几天时间!让我们写一个程序来完成它。
#------------------------------------------------我是可耻的分割线-------------------------------------------
示例代码:
#! 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
运行结果:
代码把更改文件的操作注释了,换位了打印效果。如果要使用该功能需要把最后一行的注释去掉。
标签:文件,group,Python,mo,amerFilename,euroFilename,日期,date,os 来源: https://www.cnblogs.com/lirongyang/p/9655586.html
本站声明: 1. iCode9 技术分享网(下文简称本站)提供的所有内容,仅供技术学习、探讨和分享; 2. 关于本站的所有留言、评论、转载及引用,纯属内容发起人的个人观点,与本站观点和立场无关; 3. 关于本站的所有言论和文字,纯属内容发起人的个人观点,与本站观点和立场无关; 4. 本站文章均是网友提供,不完全保证技术分享内容的完整性、准确性、时效性、风险性和版权归属;如您发现该文章侵犯了您的权益,可联系我们第一时间进行删除; 5. 本站为非盈利性的个人网站,所有内容不会用来进行牟利,也不会利用任何形式的广告来间接获益,纯粹是为了广大技术爱好者提供技术内容和技术思想的分享性交流网站。