Python Forum
Latest file with a pattern produces an error - Printable Version

+- Python Forum (https://python-forum.io)
+-- Forum: Python Coding (https://python-forum.io/forum-7.html)
+--- Forum: General Coding Help (https://python-forum.io/forum-8.html)
+--- Thread: Latest file with a pattern produces an error (/thread-31399.html)



Latest file with a pattern produces an error - tester_V - Dec-09-2020

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.


RE: Latest file with a pattern produces an error - Larz60+ - Dec-09-2020

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?


RE: Latest file with a pattern produces an error - bowlofred - Dec-09-2020

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}")



RE: Latest file with a pattern produces an error - tester_V - Dec-10-2020

(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"


RE: Latest file with a pattern produces an error - tester_V - Dec-10-2020

(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!