Python学习笔记组织文件之将美国风格日期的文件改名为欧洲风格的日期
随笔记录方便自己和同路人查阅。
#------------------------------------------------我是可耻的分割线-------------------------------------------
假定你的老板用电子邮件发给你上千个文件,文件名包含美国风格的日期(MM-DD-YYYY),需要将它们改名为欧洲风格的日期(DD-MM-YYYY)。手工 完
成这个无聊的任务可能需要几天时间!让我们写一个程序来完成它。
#------------------------------------------------我是可耻的分割线-------------------------------------------
示例代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | #! 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 |
运行结果:
代码把更改文件的操作注释了,换位了打印效果。如果要使用该功能需要把最后一行的注释去掉。
分类:
Python基础
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 从 HTTP 原因短语缺失研究 HTTP/2 和 HTTP/3 的设计差异
· AI与.NET技术实操系列:向量存储与相似性搜索在 .NET 中的实现
· 基于Microsoft.Extensions.AI核心库实现RAG应用
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· C#/.NET/.NET Core技术前沿周刊 | 第 29 期(2025年3.1-3.9)
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异