Find file with largest number in filename in each sub-directory with python?

2024/10/14 11:18:05

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.

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)

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)

Any help would be greatly appreciated!

Answer

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 itlargest = max(list_of_files)print (largest)

If I can suggest a shorter solution:

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

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

https://en.xdnf.cn/q/117960.html

Related Q&A

Selenium Python - selecting from a list on the web with no stored/embedded options

Im very new to Python so forgive me if this isnt completely comprehensible. Im trying to select from a combobox in a webpage. All the examples Ive seen online are choosing from a list where the options…

How to use a method in a class from another class that inherits from yet another class python

I have 3 classes :class Scene(object):def enter(self):passclass CentralCorridor(Scene):def enter(self):passclass Map(object):def __init__(self, start_game): passAnd the class map is initiated like this…

Finding common IDs (intersection) in two dictionaries

I wrote a piece of code that is supposed to find common intersecting IDs in line[1] in two different files. On my small sample files it works OK, but on my bigger files does not. I cannot figure out wh…

Run command line containing multiple strings from python script

Hello i am trying to autogenerate a PDF, i have made a python script that generates the wanted PDF but to generate it i have to call my_cover.py -s "Atsumi" -t "GE1.5s" -co "Ja…

Identify value across multiple columns in a dataframe that contain string from a list in python

I have a dataframe with multiple columns containing phrases. What I would like to do is identify the column (per row observation) that contains a string that exists within a pre-made list of words. Wi…

ipython like interpreter for ruby

I come from python background and am learning ruby. IPython is really awesome. I am new to ruby now, and wanted to have some sort of ipython things. As of now am having tough time, going along ruby lin…

Django dynamic verification form

Im trying to create a verification form in Django that presents a user with a list of choices, only one of which is valid.For example, for a user whose favourite pizza toppings includes pineapple and r…

Any method to denote object assignment?

Ive been studying magic methods in Python, and have been wondering if theres a way to outline the specific action of:a = MyClass(*params).method()versus:MyClass(*params).method()In the sense that, perh…

Delete lines found in file with many lines

I have an Excel file (.xls) with many lines (1008), and Im looking for lines that have anything with 2010. For example, there is a line that contains 01/06/2010, so this line would be deleted, leaving …

Combining semaphore and time limiting in python-trio with asks http request

Im trying to use Python in an async manner in order to speed up my requests to a server. The server has a slow response time (often several seconds, but also sometimes faster than a second), but works …