[英]How to find the latest file in a directory with Python
def new_report(test_report):
lists = os.listdir(test_report)
print(list)
lists.sort(key=lambda fn:os.path.getmtime(test_report + "\\" + fn))
file_new = os.path.join(test_report,lists[-1])
print(file_new)
return file_new
if __name__=="__main__":
test_report="path"
new_report(test_report)
这是我在网上找到的代码。 它用于获取目录中的最新文件,但我无法理解这一部分:
lists.sort(key=lambda fn:os.path.getmtime(test_report + "\\" + fn))
什么是test_report+"\\\\"+fn ,why +fn
实际上,这是您抓取的程序代码中的错误,或者至少是一个遗漏。 os.path.getmtime
采用文件的完整路径,因此lambda尝试在目录test_report
构建文件fn
的完整路径,但它使用非标准的,操作系统特定的定界符\\\\
它们连接在一起。
与其硬编码一个特定的分隔符,不如让python提出适合您操作系统的分隔符,
os.path.join(report_dir, fn)
可以在Python支持的任何操作系统上使用。 实际上,我看到下面使用了os.path.join
。 我不知道为什么上面也不会使用它。
此外,该程序将lists
的东西,然后打印list
是有效的,但只打印list
类型。 可能他们打算print(lists)
$ python -c 'print(list)'
<type 'list'>
这些更改一起为我们提供了最终的代码,如下所示:
import os
def new_report(test_report):
lists = os.listdir(test_report)
print(lists)
lists.sort(key=lambda fn:os.path.getmtime(os.path.join(test_report, fn)))
file_new = os.path.join(test_report,lists[-1])
print(file_new)
return file_new
if __name__=="__main__":
test_report="/tmp"
new_report(test_report)
我更改为“ / tmp”,以便可以获得实际结果,这在我的mac机上为我产生了:
$ python t.py
['powerlog', 't', 'com.apple.launchd.pFf62wnsYV', 'com.apple.launchd.bAXuv2WS1L']
/tmp/powerlog
请注意,我编写的代码按原样工作。 这就是所谓的可验证示例,因为它按编码方式运行。 提出可运行代码段始终是最佳实践,以解决您的问题! 在这种情况下,您这样做了,因为您发布了您所要求的代码。 我只是想把它扔在那里,因为我看到您是一个新的贡献者,而新贡献者的问题可能是#1遗漏的部分,使他们难以回答或难以自信地进行分析。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.