I have this this code here… it generates a list of files and folders in a directory
import os
for x in os.listdir("C:\Users"):
text = text + "\n" + x
f = open("List.txt", "w")
f.write(text)
f.close()
But how can I get it to do two things…
Firstly well read whats in the folders and keep going until there is only a child.
Secondly when it goes down a level it adds a tab. Like this
Level 1 (parent)
Level 2 (child)
How can I get it to add that tab in? For infinite amount of levels?
Use
os.walk()instead:In each loop,
pathis the full path to the directory the filenames and dirnames are directly contained in. By usingos.path.relpathwe extract the ‘local’ path, count the depth and use that for the number of tabs to prepend each filename with.