Python – Listing files in directory and sub-directories,sort files by creation date and select top X files

Posted: October 21, 2019 in Scripts
    from itertools import islice 

    def getListOfFiles(dirName):
    # create a list of file and sub directories 
    # names in the given directory 

    listOfFile = os.listdir(dirName)
    allFiles = list()
    # Iterate over all the entries
    for entry in listOfFile:
        # Create full path
        fullPath = os.path.join(dirName, entry)
        # If entry is a directory then get the list of files in this directory 
        if os.path.isdir(fullPath):
            allFiles = allFiles + getListOfFiles(fullPath)
    return allFiles  

dirName = "C:\SIEMLogs\Email"
listOfFiles = getListOfFiles(dirName)

# sort filenames by creation date (ascending)

sorted_files = sorted(listOfFiles, key=os.path.getmtime)

# select top 5 elements from sorted list

top_files = islice(sorted_files,5)

# Print top 5 files
for elem in top_files:

# Number of files in sub directories

cpt = sum([len(files) for r, d, files in os.walk("C:\SIEMLogs\Email")])

print cpt

Listing files in directory (without sub directories),sorting by creation date (ascending) and count of total files:

path = "C:\SIEMLogs\Email"
name_list = os.listdir(path)
full_list = [os.path.join(path,i) for i in name_list]
time_sorted_list = sorted(full_list, key=os.path.getmtime)

for a in time_sorted_list:
    print a

# Number of files in Directory only

path, dirs, files = next(os.walk("C:\SIEMLogs\Email"))
file_count = len(files)

print file_count

Leave a Reply

Fill in your details below or click an icon to log in: Logo

You are commenting using your account. Log Out /  Change )

Google photo

You are commenting using your Google account. Log Out /  Change )

Twitter picture

You are commenting using your Twitter account. Log Out /  Change )

Facebook photo

You are commenting using your Facebook account. Log Out /  Change )

Connecting to %s