Я пришел сюда в поисках того же и используется dhobbs ответ для меня. Как способ поблагодарить сообщество, я добавил несколько аргументов для записи в файл, как сказал akshay, и сделал показ файлов необязательным, так что это не так бит вывода. Также сделал отступ дополнительным аргументом, чтобы вы могли его изменить, так как некоторые из них должны быть равны 2 и другие. 4.
Используются различные циклы, поэтому один из них не показывает файлы, не проверяет, требуется ли им на каждой итерации.
Надеюсь, что это поможет кому-то другому, поскольку ответ дхоббс мне помог. Большое спасибо.
def showFolderTree(path,show_files=False,indentation=2,file_output=False):
"""
Shows the content of a folder in a tree structure.
path -(string)- path of the root folder we want to show.
show_files -(boolean)- Whether or not we want to see files listed.
Defaults to False.
indentation -(int)- Indentation we want to use, defaults to 2.
file_output -(string)- Path (including the name) of the file where we want
to save the tree.
"""
tree = []
if not show_files:
for root, dirs, files in os.walk(path):
level = root.replace(path, '').count(os.sep)
indent = ' '*indentation*(level)
tree.append('{}{}/'.format(indent,os.path.basename(root)))
if show_files:
for root, dirs, files in os.walk(path):
level = root.replace(path, '').count(os.sep)
indent = ' '*indentation*(level)
tree.append('{}{}/'.format(indent,os.path.basename(root)))
for f in files:
subindent=' ' * indentation * (level+1)
tree.append('{}{}'.format(subindent,f))
if file_output:
output_file = open(file_output,'w')
for line in tree:
output_file.write(line)
output_file.write('\n')
else:
# Default behaviour: print on screen.
for line in tree:
print line
Я предложил бы использовать 'os.walk () ', но похоже, что вы уже там ... что вы пробовали? –
Я думаю, это потому, что я не совсем понимаю кортеж. Я знаю, как перечислить все каталоги и все файлы по отдельности, но я не знаю, как перечислить файлы и поддиректоры каталога без перекрывающихся вещей. – user18115
См. Ответ на [этот вопрос] (http://stackoverflow.com/questions/120656/directory-listing-in-python) –