Python program to recursively list files and directories

Last updated on 12th January 2016

This Python program uses functions provided by the os module recursively navigate through a directory tree while listing the directories, subdirectories and files. In case of files, the program also show its size and modification time.

The three main functions used in the program are:

  • os.walk(): This function traverses the directory tree and for each directory in the tree, it returns a 3-tuple (directorypath, directoryname, filename)
  • os.stat(): This functios returns the file attributes such as size and modified time.
  • os.path.join(): To join the paths and filenames intelligently.

Additionally the program uses math functions to convert file size to Kilo bytes, Megabytes etc., and Time functions to display file modification date and time.

Program Source

#Import os module
import os
#Import math and time module
import math,time

#Set listing start location
start_path = "C:\Samples"
dir_count = 0
file_count = 0

#Traverse directory tree
for (path,dirs,files) in os.walk(start_path):
    print('Directory: {:s}'.format(path))
    dir_count += 1
    #Repeat for each file in directory
    for file in files:
        fstat = os.stat(os.path.join(path,file))

        # Convert file size to MB, KB or Bytes
        if (fstat.st_size > 1024 * 1024):
            fsize = math.ceil(fstat.st_size / (1024 * 1024))
            unit = "MB"
        elif (fstat.st_size > 1024):
            fsize = math.ceil(fstat.st_size / 1024)
            unit = "KB"
        else:
            fsize = fstat.st_size
            unit = "B"

        mtime = time.strftime("%X %x", time.gmtime(fstat.st_mtime))
        
         # Print file attributes
        print('\t{:15.15s}{:8d} {:2s} {:18s}'.format(file,fsize,unit,mtime))
        file_count += 1
 # Print total files and directory count
print('\nFound {} files in {} directories.'.format(file_count,dir_count))    
    

Sample Output


Directory: C:\Samples
Directory: C:\Samples\Logs
	LogFile-2015092     121 B  15:38:27 01/12/16 
	LogFile-2015092      83 B  07:57:03 09/23/15 
	LogFile-2015092       4 KB 15:38:37 01/12/16 
Directory: C:\Samples\Pictures
	Hydrangeas.jpg      582 KB 05:32:31 07/14/09 
	Jellyfish.jpg       758 KB 05:32:31 07/14/09 
Directory: C:\Samples\Pictures\text
	textfile1.txt        81 B  07:57:29 09/23/15 

Found 6 files in 4 directories.


Post a comment

Comments

Nothing yet..be the first to share wisdom.