【问题标题】:Get file modification date? [duplicate]获取文件修改日期? [复制]
【发布时间】:2015-02-19 06:24:45
【问题描述】:

如果文件存在,我使用以下代码获取文件的修改日期:

if os.path.isfile(file_name):
    last_modified_date = datetime.fromtimestamp(os.path.getmtime(file_name))
else:
    last_modified_date = datetime.fromtimestamp(0)

有没有更优雅/更简洁的方式?

【问题讨论】:

标签: python file


【解决方案1】:

你可以使用异常处理;无需先测试文件是否存在,如果不存在则捕获异常:

try:
    mtime = os.path.getmtime(file_name)
except OSError:
    mtime = 0
last_modified_date = datetime.fromtimestamp(mtime)

这是请求宽恕而不是许可。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2012-05-16
    • 2014-06-08
    • 2016-12-09
    • 1970-01-01
    • 2010-09-12
    • 2011-04-09
    相关资源
    最近更新 更多