Search code examples
pythonreadfile

Read latest file with a filename contains string in python


Assume that I have a list of file like this:

  • abc_name.txt
  • def_name.txt
  • ghj_name.txt
  • abcdefghj.txt
  • xyz.txt

I knew how to read latest file by using max(list_of_files, key=os.path.getmtime), but it could be any last created file.

I want to read file that contains 'name' in its name and this file was last created (for example "def_name.txt").

How can I do that in python?

Many thanks.


Solution

  • Suppose you run a bash command:

    $ ch /tmp
    $ touch abc_name.txt def_name.txt ghj_name.txt abcdefghj.txt xyz.txt
    

    From Python you can use pathlib to both glob the directory where the files are and have fine control of what time element you are testing.

    from pathlib import Path 
    
    p=Path('/tmp')
    
    max([fn for fn in p.glob('*.txt') if 'name' in str(fn)], key=lambda f: f.stat().st_mtime)
    
    # /tmp/ghj_name.txt 
    

    You can also change your glob so only files with name in them are returned:

    max([fn for fn in p.glob('*name*.txt')], key=lambda f: f.stat().st_mtime)
    
    # same result