Skip to content

Instantly share code, notes, and snippets.

@jorge-lavin
Created March 2, 2015 10:07
Show Gist options
  • Save jorge-lavin/1b67d9709cdc5b948dbd to your computer and use it in GitHub Desktop.
Save jorge-lavin/1b67d9709cdc5b948dbd to your computer and use it in GitHub Desktop.
Print tree structure of folder with indentation
import os
def list_files(startpath):
for root, dirs, files in os.walk(startpath):
level = root.replace(startpath, '').count(os.sep)
indent = ' ' * 4 * (level)
yield ('{}{}/'.format(indent, os.path.basename(root)))
subindent = ' ' * 4 * (level + 1)
for f in files:
yield ('{}{}'.format(subindent, f))
if __name__ == '__main__':
films_folder = '/drives/e/Peliculas'
films_file = 'pelis.txt'
with open(films_file, 'w') as file_pelis:
for file_listed in list_files(films_folder):
# \n{}.format() prints newlines as expected
file_pelis.write('\n{}'.format(file_listed))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment