如何获取子目录所有文件及指定文件列表的创建日期?
解决文件创建日期相关问题
嘿,我来帮你搞定这两个关于文件创建日期的问题!
1. 获取子目录中所有文件的创建日期
要获取子目录里所有文件的创建日期,需要注意不同操作系统的差异——Windows 和类 Unix 系统(macOS、Linux)对文件创建时间的存储逻辑不太一样。这里推荐两种实用的实现方式:
方式一:用 pathlib(Python 3.4+,更简洁跨平台)
pathlib 是 Python 3.4 引入的面向对象路径模块,语法更直观,且大部分系统都支持通过 stat().birthtime 获取创建时间:
import pathlib from datetime import datetime def get_all_files_creation_dates(root_path): creation_dates = {} # 遍历根路径下所有子目录的文件 for file_path in pathlib.Path(root_path).rglob('*'): if file_path.is_file(): # 获取创建时间戳并转成可读格式 creation_timestamp = file_path.stat().birthtime readable_date = datetime.fromtimestamp(creation_timestamp).strftime('%Y-%m-%d %H:%M:%S') creation_dates[str(file_path)] = readable_date return creation_dates # 使用示例 dates = get_all_files_creation_dates('/your/root/directory') for file, date in dates.items(): print(f"{file}: {date}")
方式二:用 os.walk 配合平台判断(兼容旧版本 Python)
如果你用的是 Python 3.4 之前的版本,可以用 os.walk 遍历,再根据操作系统选择对应的时间获取方式:
import os from datetime import datetime import platform def get_all_files_creation_dates(root_path): creation_dates = {} for root, dirs, files in os.walk(root_path): for file in files: file_path = os.path.join(root, file) if platform.system() == 'Windows': # Windows 下 os.path.getctime() 返回的就是创建时间 creation_timestamp = os.path.getctime(file_path) else: # macOS/Linux 下优先用 st_birthtime(创建时间),部分 Linux 可能没有该属性, fallback 到修改时间 stat_info = os.stat(file_path) try: creation_timestamp = stat_info.st_birthtime except AttributeError: creation_timestamp = stat_info.st_mtime readable_date = datetime.fromtimestamp(creation_timestamp).strftime('%Y-%m-%d %H:%M:%S') creation_dates[file_path] = readable_date return creation_dates
2. 从已有文件路径列表获取每个文件的创建日期
你已经写了获取文件路径的 find 函数,只需要在此基础上遍历路径列表,对每个文件单独获取创建日期即可。这里直接给你整合后的代码:
import os import fnmatch from datetime import datetime import platform # 你原有的文件路径获取函数 def find(pattern, path): result = [] for root, dirs, files in os.walk(path): for name in files: if fnmatch.fnmatch(name, pattern): result.append(os.path.join(root, name)) return result # 新增函数:根据路径列表获取每个文件的创建日期 def get_files_creation_dates(file_paths): creation_dates = {} for file_path in file_paths: # 先确保路径指向的是文件(而非目录) if os.path.isfile(file_path): if platform.system() == 'Windows': creation_timestamp = os.path.getctime(file_path) else: stat_info = os.stat(file_path) try: creation_timestamp = stat_info.st_birthtime except AttributeError: creation_timestamp = stat_info.st_mtime readable_date = datetime.fromtimestamp(creation_timestamp).strftime('%Y-%m-%d %H:%M:%S') creation_dates[file_path] = readable_date return creation_dates # 使用示例 file_list = find('*.txt', '/your/target/path') # 替换成你的文件匹配规则和目标路径 file_dates = get_files_creation_dates(file_list) for file, date in file_dates.items(): print(f"{file} 的创建日期:{date}")
需要注意的是:部分 Linux 发行版可能没有记录文件的创建时间(st_birthtime 属性不存在),这时候我们会 fallback 到文件的最后修改时间(st_mtime),这是目前能做到的最优兼容方案。
内容的提问来源于stack exchange,提问作者T17
相关产品推荐
相关产品推荐

