Search code examples
pythonglob

Find the newest file in a directory in python


I'm trying to find the newest file in a directory. However, max() is returning a "max() arg is empty sequence error" I've even tried passing in the exact path instead of the path variable.

def function(path):
   max(glob.iglob('path\*.map'), key=os.path.getctime)
   ...

Any ideas?


Solution

  • In your function, path is passed in as an argument, however, your glob spec is using the literal string 'path\*.map'. So, unless you actually have a directory named path that contains .map files, iglob() will return an empty list, and max() will raise the exception that you see.

    Instead you should substitute the value of the path variable into the glob spec string:

    glob.iglob(r'{}\*.map'.format(path))
    

    Now, assuming that the path and .map files do exist, you can find the most recent.

    Also, you should use os.path.join() to construct the glob spec. Your function would then look like this:

    def most_recent_map_file(path):
        glob_pattern = os.path.join(path, '*.map')
        return max(glob.iglob(glob_pattern), key=os.path.getctime)
    

    os.path.join() is preferable because it will handle the different path separators of different OSes - \ for Windows, / for *nix.