capture directory listing to CSV


/ Published in: Python
Save to your folder(s)

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


Copy this code and paste it in your HTML
  1. # Code courtesy of "pepr"
  2. # http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_23347326.html
  3. import csv
  4. import glob
  5. import os
  6. import sys
  7. import time
  8.  
  9. def dirlister(dir_mask):
  10. '''Generator that returns full names of the searched files.'''
  11.  
  12. # Split the path with mask into path and mask.
  13. root, mask = os.path.split(dir_mask)
  14.  
  15. # Traverse the directories from the root. Use globbing
  16. # inside of each dirpath below. Ignore the dirnames
  17. # and filenames lists.
  18. for dirpath, dirnames, filenames in os.walk(root):
  19. fmask = os.path.join(dirpath, mask)
  20. lst = glob.glob(fmask)
  21.  
  22. # Traverse the list of results of the glob().
  23. # Yield the filenames only.
  24. for fname in lst:
  25. if os.path.isfile(fname):
  26. yield fname
  27.  
  28.  
  29. def getFileInfo(fname):
  30. '''Get the file info and return the tuple of formated values.'''
  31. assert os.path.isfile(fname)
  32. return ( time.strftime('%d/%m/%Y', time.localtime(os.path.getmtime(fname))),
  33. str(os.path.getsize(fname)),
  34. os.path.split(fname)[1],
  35. os.path.split(fname)[0]
  36. )
  37.  
  38.  
  39. if __name__=='__main__':
  40.  
  41. # Get the arguments.
  42. assert len(sys.argv)==3
  43. outfname = sys.argv[1]
  44. dir_mask = sys.argv[2]
  45.  
  46. # Open the output file and configure the csv writer.
  47. fout = open(outfname, 'wb')
  48. writer = csv.writer(fout, quoting=csv.QUOTE_ALL)
  49. writer.writerow(["DATE","BYTES","FILENAME","PATH"])
  50.  
  51. # Search for all the wanted files and write the info for each.
  52. for fname in dirlister(dir_mask):
  53. writer.writerow(getFileInfo(fname))
  54.  
  55. # Do not forget to close the output file.
  56. fout.close()

URL: http://www.experts-exchange.com/Programming/Languages/Scripting/Python/Q_23347326.html

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.