FabianCook
FabianCook

Reputation: 20557

Generating a list of files

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?

Upvotes: 0

Views: 77

Answers (1)

Martijn Pieters
Martijn Pieters

Reputation: 1121476

Use os.walk() instead:

start = r'C:\Users'
entries = []
for path, filenames, dirnames in os.walk(start):
    relative = os.path.relpath(path, start)
    depth = len(os.path.split(os.pathsep))
    entries.extend([('\t' * depth) + f for f in filenames])
with open("List.txt", "w") as output:
    output.write('\n'.join(entries))

In each loop, path is the full path to the directory the filenames and dirnames are directly contained in. By using os.path.relpath we extract the 'local' path, count the depth and use that for the number of tabs to prepend each filename with.

Upvotes: 3

Related Questions