1 回答

TA贡献1852条经验 获得超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)成对的列表,而不仅仅是将它们打印到屏幕上。
添加回答
举报