如何使用Python在目录中查找最新文件
这是我在网上找到的代码。它用于获取目录中的最新文件,但我无法理解这一部分:如何使用Python在目录中查找最新文件,python,sorting,lambda,Python,Sorting,Lambda,这是我在网上找到的代码。它用于获取目录中的最新文件,但我无法理解这一部分: 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.
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)
什么是
test\u report+“\\”+fn,为什么+fn
这实际上是您获取的程序代码中的一个bug,或者至少是一个遗漏os.path.getmtime
获取文件的完整路径,因此lambda试图在目录test\u report
中构建文件fn
的完整路径,但它使用非标准的、特定于操作系统的分隔符\
将它们连接起来
与其硬编码特定的分隔符,不如让python提供适合您的操作系统的分隔符
lists.sort(key=lambda fn:os.path.getmtime(test_report + "\\" + fn))
它可以在Python支持的任何操作系统上工作。实际上我看到下面使用了os.path.join
。我不知道为什么上面不会用到它
此外,程序将列表
设置为某物,然后打印有效的列表
,但仅打印列表
类型。可能他们想打印(列表)
我改为“/tmp”以便获得实际结果,这在我的mac上为我产生了以下结果:
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)
请注意,我编写的代码按原样工作。这就是所谓的a,因为它是按代码运行的。为您的问题提供一段可运行的代码始终是最佳实践!在本例中,您这样做了,因为您发布了您所询问的代码。我只是想把它放在这里,因为我看到你是一个新的投稿人,而这可能是新投稿人问题中缺失的一部分,使他们难以回答或难以自信地分析 这是一个lambda函数,它将根据键lambda函数对文件名列表的内容进行排序。因此,列表中的每个元素都是lambda函数的
fn
参数。lambda函数将设置文件的mtime,并根据该mtime对文件进行排序。为了让事情更清楚,fn
代表此上下文中的文件名。非常感谢您的回复。我会记住你的建议。我是一个新的贡献者,也是python的新用户。下面是另一个问题。我知道os.path.join()可以将多个路径合并为一个路径,但是为什么os.path.join(test_report,fn)可以表示文件的全名,我知道test_report是文件的目录,为什么fn是文件的名称。正在向thanksLists.sort传递一个lambda,其参数是listdir中的每个文件名。应该说清楚。
$ 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)
$ python t.py
['powerlog', 't', 'com.apple.launchd.pFf62wnsYV', 'com.apple.launchd.bAXuv2WS1L']
/tmp/powerlog