使用python在每个子目录中查找文件名中编号最大的文件?

时间:2018-06-20 14:48:40

标签: python arrays sorting max

我试图在每个子目录的文件名中找到编号最大的文件。这样我就可以完成打开每个子目录中的最新文件的操作。每个文件将遵循日期filename.xlsx的命名对流。

例如20180620文件名.xlsx

我有一个代码可用于在一个目录中搜索最大号码。

dirname = py.path.local(path)

list_of_files = []

for file in dirname.visit(fil='*.xlsx', bf=True):
    list_of_files.append(file)

largest = max(list_of_files)
print (largest)

我对Python还是很陌生,我还不太清楚如何使这种样式的代码正常工作,以查找目录中每个子目录中编号最大的文件。我已经尝试了以下代码的多种变体,但是我无法让它仅打印出每个子目录中编号最大的文件。

list_of_files = []

for root, dirs, files in os.walk(path):
    for name in files:
        if name.endswith((".xlsx")):
            list_of_files.append(files)
            largest = max(list_of_files)
            print (largest)

任何帮助将不胜感激!

1 个答案:

答案 0 :(得分:1)

您的第二个代码块几乎完成了您想做的事情,您只是错误地嵌套了操作。

for root, dirs, files in os.walk(path):
    # new subdir, so let's make a new...
    list_of_files = []
    for name in files:
        if name.endswith((".xlsx")):
            list_of_files.append(name)  # you originally appended the list of all names!
    # once we're here, list_of_files has all the filenames in it,
    # so we can find the largest and print it
    largest = max(list_of_files)
    print (largest)

如果我可以建议一个较短的解决方案:

[(root, max(fname for fname in files if fname.endswith(".xlsx"))) for
 root, dirs, files in os.walk(path)]

这将为您提供(dirname, largest_filename)对的列表,而不仅仅是将它们打印到屏幕上。

相关问题