Search code examples
pythonfiledirectorylistdir

Python newest file in a directory


I am working on a script where I am trying to list the newest file ending with .xls. It should be easy, but I am receiving some errors.

Code:

for file in os.listdir('E:\\Downloads'):
    if file.endswith(".xls"):
        print "",file
        newest = max(file , key = os.path.getctime)
        print "Recently modified Docs",newest

Error:

Traceback (most recent call last):
  File "C:\Python27\sele.py", line 49, in <module>
    newest = max(file , key = os.path.getctime)
  File "C:\Python27\lib\genericpath.py", line 72, in getctime
    return os.stat(filename).st_ctime
WindowsError: [Error 2] The system cannot find the file specified: 'u'

Solution

  • newest = max(file , key = os.path.getctime)
    

    This is iterating over the characters in your filename instead of your list of files.

    You are doing something like max("usdfdsf.xls", key = os.path.getctime)instead of max(["usdfdsf.xls", ...], key = os.path.getctime)

    You probably want something like

    files = [x for x in os.listdir('E:\\Downloads') if x.endswith(".xls")]
    newest = max(files , key = os.path.getctime)
    print "Recently modified Docs",newest
    

    You may want to also improve the script so that it works if you're not in the Downloads directory:

    files = [os.path.join('E:\\Downloads', x) for x in os.listdir('E:\\Downloads') if x.endswith(".xls")]