获取文件创建和修改日期/时间的最佳跨平台方式是什么,它适用于 Linux 和 Windows?
原文由 Mark Biek 发布,翻译遵循 CC BY-SA 4.0 许可协议
获取文件创建和修改日期/时间的最佳跨平台方式是什么,它适用于 Linux 和 Windows?
原文由 Mark Biek 发布,翻译遵循 CC BY-SA 4.0 许可协议
以跨平台的方式获取某种修改日期很容易 - 只需调用 os.path.getmtime(path)
你将获得 path
文件最后修改时间的 Unix 时间戳。
另一方面,获取文件 创建 日期非常繁琐且依赖于平台,甚至在三大操作系统之间也有所不同:
ctime
(记录在 https://msdn.microsoft.com/en-us/library/14h5k7ff.aspx )存储其创建日期。您可以通过 os.path.getctime()
或 .st_ctime
调用结果的属性在 Python 中访问 os.stat()
。这在 Unix 上 _不起作用_,其中 ctime
是文件属性 或 内容的最后一次更改。.st_birthtime
调用结果的属性 os.stat()
。ext4
将它们存储在 st_crtime
中),但 Linux 内核 无法访问它们;特别是,它从 stat()
在 C 中调用返回的结构,从最新的内核版本开始, 不包含任何创建日期字段。您还可以看到标识符 st_crtime
目前在 Python 源代码 中没有任何特征。至少如果你在 ext4
上, 数据 附加到文件系统中的索引节点,但没有方便的方法来访问它。The next-best thing on Linux is to access the file’s mtime
, through either os.path.getmtime()
or the .st_mtime
attribute of an os.stat()
result.这将为您提供文件内容的最后一次修改时间,这对于某些用例来说可能已经足够了。
将所有这些放在一起,跨平台代码应该看起来像这样……
import os
import platform
def creation_date(path_to_file):
"""
Try to get the date that a file was created, falling back to when it was
last modified if that isn't possible.
See http://stackoverflow.com/a/39501288/1709587 for explanation.
"""
if platform.system() == 'Windows':
return os.path.getctime(path_to_file)
else:
stat = os.stat(path_to_file)
try:
return stat.st_birthtime
except AttributeError:
# We're probably on Linux. No easy way to get creation dates here,
# so we'll settle for when its content was last modified.
return stat.st_mtime
原文由 Mark Amery 发布,翻译遵循 CC BY-SA 3.0 许可协议
2 回答5.1k 阅读✓ 已解决
2 回答1.1k 阅读✓ 已解决
4 回答1.4k 阅读✓ 已解决
3 回答1.3k 阅读✓ 已解决
3 回答1.2k 阅读✓ 已解决
1 回答1.7k 阅读✓ 已解决
1 回答1.2k 阅读✓ 已解决
在 Python 3.4 及更高版本中,您可以使用面向对象的 pathlib 模块 接口,其中包含大部分 os 模块的包装器。这是获取文件统计信息的示例。
有关
os.stat_result
包含的内容的更多信息,请参阅 文档。对于您想要的修改时间fname.stat().st_mtime
:如果你想要 Windows 上的创建时间,或者 Unix 上的最新元数据更改,你可以使用
fname.stat().st_ctime
:本文 为 pathlib 模块提供了更多有用的信息和示例。