Search code examples
pythonfindfileinfo

Using Python, how do I get an array of file info objects, based on a search of a file system?


Currently I have a bash script which runs the find command, like so:

find /storage/disk-1/Media/Video/TV -name *.avi -mtime -7

This gets a list of TV shows that were added to my system in the last 7 days. I then go on to create some symbolic links so I can get to my newest TV shows.

I'm looking to re-code this in Python, but I have a few questions I can seem to find the answers for using Google (maybe I'm not searching for the right thing). I think the best way to sum this up is to ask the question:

How do I perform a search on my file system (should I call find?) which gives me an array of file info objects (containing the modify date, file name, etc) so that I may sort them based on date, and other such things?


Solution

  • import os, time
    
    allfiles = []
    now = time.time()
    
    # walk will return triples (current dir, list of subdirs, list of regular files)
    # file names are relative to dir at first
    for dir, subdirs, files in os.walk("/storage/disk-1/Media/Video/TV"):
        for f in files:
            if not f.endswith(".avi"):
                continue
            # compute full path name
            f = os.path.join(dir, f)
            st = os.stat(f)
            if st.st_mtime < now - 3600*24*7:
                # too old
                continue
            allfiles.append((f, st))
    

    This will return all files that find also returned, as a list of pairs (filename, stat result).