使用python在每个子目录中查找文件名中编号最大的文件? [英] Find file with largest number in filename in each sub-directory with python?

查看:76
本文介绍了使用python在每个子目录中查找文件名中编号最大的文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I am trying to find the file with the largest number in the filename in each subdirectory. This is so I can acomplish opening the most recent file in each subdirectory. Each file will follow the naming convetion of date filename.xlsx.

例如20180620文件名.xlsx

Ex. 20180620 file name.xlsx

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

I have a code that works for searching one directory for largest numbers.

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

I am pretty new to Python and I can't quite figure out how to make this style of code work looking for the file with the largest number in each subdirectory within a directory. I have tried many variations off of this following code, but I can't get it to print out just the file with the largest number from each subdirectory.

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)

任何帮助将不胜感激!

推荐答案

您的第二个代码块几乎完成了 您要执行的操作,只是您的操作嵌套不正确.

Your second code block does almost what you want to do, you've just nested your operations incorrectly.

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)

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

If I can suggest a shorter solution:

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

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

This will give you a list of (dirname, largest_filename) pairs, rather than just printing them to the screen.

这篇关于使用python在每个子目录中查找文件名中编号最大的文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆