Thursday, 12 January 2012

Python: Create a file listing a folders contents

Our co-ord was just trying to get some info together so I come up with this simple little script to print the contents of a specified folder into a dated file.
I'm aware there are better methods of writing the file (using the list and write each item individually in loop etc), but it was short and does the job.

To get the date, I simply used the datetime module and retrieved today's date (as stipulated on local machine), then converted it to a familiar format.
For writing the file, I simply joined a sorted list of files found into a string separated by a newline, opened a writeable doc, deposited the data and closed it to allow access. import os import datetime def ld_listFiles(path,resultPath): fileString='\n'.join(sorted(os.listdir(path))) date=d.isoformat() filePath=resultPath+'filesListResults_'+date+'.txt' thefile=open(filePath,'w') thefile.write(fileString) thefile.close() return fileString # ld_listFiles('C:/Users/Lee/Desktop/Documents/','C:/Users/Lee/Desktop/')
...and of course this can then be furthered for error checking (making sure paths exist, folders contain files etc), nativePath conversion (not sure of correct terminology), specify file extensions/types, folder contents, file sizes, modification date etc. This is just a very simple example (and perhaps not a great one, but it works).
In fact I think I might spend some time in creating a decent version.
Any tips, suggestions etc, are more than welcome!