Python Forum

Full Version: Latest file with a pattern produces an error
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi,
I'm trying to find the latest file in a directory but only if a file has a digit in its name.
I globbed the files that have "digit/digits" in the name but after adding "max(fname, key=os.path.getctime)"
The script produces a bunch of errors Confused .

import os
import glob

for fname in glob.glob('C:\\02\\*[0-9].*'):
    print (fname)
    lt_file = max(fname, key=os.path.getctime)
    
    print ("Latest file -->>", lt_file)
Thank you.
I take it from your glob statement that the digit must come on the end of the filename stem (part before the .) is that correct?
fname is set repeatedly to each file in turn inside the loop. You can't ask for the max of one thing.

You can ask for the max of all of them together though.

g = glob.glob('C:\02\*[0-9].*')
lt_file = max(g, key=os.path.getctime)
print(f"Latest file -->> {lt_file}")
(Dec-09-2020, 02:11 AM)Larz60+ Wrote: [ -> ]I take it from your glob statement that the digit must come on the end of the filename stem (part before the .) is that correct?

That is correct.
Line this, "something01.log"
(Dec-09-2020, 04:23 AM)bowlofred Wrote: [ -> ]fname is set repeatedly to each file in turn inside the loop. You can't ask for the max of one thing.

You can ask for the max of all of them together though.

g = glob.glob('C:\02\*[0-9].*')
lt_file = max(g, key=os.path.getctime)
print(f"Latest file -->> {lt_file}")

I see your point!
I thought I should iterate over the files to find the oldest one.

Thank you!