/ Published in: Python
I needed a small python program or code snippet to recursively search a directory tree for the specified file pattern and save the results to CSV
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
# Code courtesy of "pepr" # http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_23347326.html import csv import glob import os import sys import time def dirlister(dir_mask): '''Generator that returns full names of the searched files.''' # Split the path with mask into path and mask. root, mask = os.path.split(dir_mask) # Traverse the directories from the root. Use globbing # inside of each dirpath below. Ignore the dirnames # and filenames lists. for dirpath, dirnames, filenames in os.walk(root): fmask = os.path.join(dirpath, mask) lst = glob.glob(fmask) # Traverse the list of results of the glob(). # Yield the filenames only. for fname in lst: if os.path.isfile(fname): yield fname def getFileInfo(fname): '''Get the file info and return the tuple of formated values.''' assert os.path.isfile(fname) return ( time.strftime('%d/%m/%Y', time.localtime(os.path.getmtime(fname))), str(os.path.getsize(fname)), os.path.split(fname)[1], os.path.split(fname)[0] ) if __name__=='__main__': # Get the arguments. assert len(sys.argv)==3 outfname = sys.argv[1] dir_mask = sys.argv[2] # Open the output file and configure the csv writer. fout = open(outfname, 'wb') writer = csv.writer(fout, quoting=csv.QUOTE_ALL) writer.writerow(["DATE","BYTES","FILENAME","PATH"]) # Search for all the wanted files and write the info for each. for fname in dirlister(dir_mask): writer.writerow(getFileInfo(fname)) # Do not forget to close the output file. fout.close()
URL: http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_23347326.html