Search code examples
python-2.7operating-systemdirectorysubdirectorylast-modified

Search the last modified ".mxd" files in directory and sub-directory- Python Error


I try to find the last modified files which end with ".mxd" in directory and sub-directory and print the modified time, using this code:

import os

max_mtime = 0
for dirname,subdirs,files in os.walk(r"G:\desktop\Project"):
    for fname in files:
        if fname.endswith(".mxd"):
            full_path = os.path.join(dirname, fname)
            mtime = os.stat(full_path).st_mtime
            if mtime > max_mtime:
                max_mtime = mtime
                max_dir = dirname
                max_file = fname
                print os.path.getatime(fname)

print max_dir, max_file

but when i run this code it raise an error and i don't understand what is my mistake:

WindowsError: [Error 2] : 'project.mxd'

I red How to get file creation & modification date/times in Python? but didn't found any way to solve my problem.


Solution

  • finaly, this code worked for well:

    import os,time,datetime,glob
    
    path = r"G:\desktop\Project"
    for dirname,subdirs,files in os.walk(path):
        max_mtime = 0
        max_dir = ""
        max_file =""
        for fname in files:
            mtime=0
            if fname.endswith(".mxd"):
                full_path = os.path.join(dirname, fname)
                mtime = os.stat(full_path).st_mtime
                if mtime > max_mtime:
                    max_mtime = mtime
                    max_dir = dirname
                    max_file = fname
        print max_dir, max_file
        print