Find File With Largest Number In Filename In Each Sub-directory With Python?
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
Solution 1:
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 inos.walk(path)]
This will give you a list of (dirname, largest_filename)
pairs, rather than just printing them to the screen.
Post a Comment for "Find File With Largest Number In Filename In Each Sub-directory With Python?"