【问题标题】:Latest file path is not returned using glob in python在 python 中使用 glob 不返回最新的文件路径
【发布时间】:2019-05-02 15:37:27
【问题描述】:

我正在尝试监视日志文件夹。如果创建了任何新文件,则必须返回文件路径。为此,我使用了以下代码:

import glob
list_of_files_in_real_predicted = glob.iglob(r'logging\real_predicted\*')
latest_file_in_real_predicted = max(list_of_files_in_real_predicted, key=os.path.getctime)
print(latest_file_in_real_predicted)

返回的输出是:logging\real_predicted\log935.csv
而不是:logging\real_predicted\log0.csv

这是文件夹的快照,可以看到最新创建的文件;

请告诉我如何获取最新创建的文件。

【问题讨论】:

  • 截图中显示的是Date modified,所以你必须使用os.path.getmtime来获取这个值。
  • 我建议添加os.stat('log0.csv')os.stat('log935.csv) 的输出,因为os.path.getctime 在下面使用os.stat

标签: python python-3.x file


【解决方案1】:

getctimegetmtime 不同。您在 Windows 中看到的(以及真正有用且广泛使用的)是修改时间。你想要:

latest_file_in_real_predicted = max(list_of_files_in_real_predicted, key=os.path.getmtime)

修改时间与文件内容的最后修改时间一致。可能是每个人都使用它的原因。

getctime 甚至不是文件创建日期:

ctime 表示上次更改 inode 的时间

来源:Difference between python - getmtime() and getctime() in unix system

【讨论】:

  • 好的,让我看看。可能这就是我所缺少的。
  • 不可能是别的。
猜你喜欢
  • 2011-07-02
  • 2020-01-21
  • 2019-05-27
  • 1970-01-01
  • 2013-01-22
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多