If you want a list of directories and the files they contain, this program will log such information to a file for you. For those wondering how to walk directories and their contents, this little recipe provides an engine
function that provides a simple demonstration of the os.walk
function.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 | import os, sys
def main(path=''):
if len(sys.argv) == 1 and path:
try:
assert os.path.isdir(path)
engine(path)
except:
print 'ERROR: Internal Path'
else:
path = ' '.join(sys.argv[1:])
try:
assert os.path.isdir(path)
engine(path)
except:
print os.path.basename(sys.argv[0]), '<directory>'
def engine(path):
log = open('files.log', 'w')
for path, dirs, files in os.walk(path):
log.write('%s\n' % path)
for name in files:
log.write('\t%s\n' % name)
log.write('\n')
log.close()
if __name__ == '__main__':
main('C:\\')
|
Tags: demonstration