0

我在这里有这个代码......它在目录中生成文件和文件夹的列表

import os
for x in os.listdir("C:\Users"):
    text = text + "\n" + x
f = open("List.txt", "w")
f.write(text)
f.close()

但是我怎样才能让它做两件事......

首先仔细阅读文件夹中的内容并继续前进,直到只有一个孩子。

其次,当它下降一个级别时,它会添加一个选项卡。像这样

Level 1 (parent)
    Level 2 (child)

我怎样才能让它添加该选项卡?对于无限数量的水平?

4

1 回答 1

3

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.

于 2012-09-29T18:27:22.247 回答