Reputation: 43
Working on a school project... I have a python list object (obtained from a text file) that contains an entire directory listing(about 400K items). Is there a module to organize this list or text file into a file tree structure automatically?
For example, the root starts the list "/". followed by the first folder in it, all the way out to the last file in the path "/folder1/sub-folder_last/lastfile.txt
This goes all the way to the very last item "/last_folder_in_root"
out to the very last sub folder in that "/last_folder_in_root/last_sub_folder/last_file.txt"
I have been searching for a good start point but the ambiguity in searching gets me nothing but os, os walk items. Hoping there is already something out there that will run through this and separate sub items with a tab or something similar.
end output would be something similar to:
/
/first_folder
/first_sub_folder
/file.txt
/second_folder
/last_folder
/last_sub_fodler
/last_file.txt
I searched through several libraries but was unable to find one that supported this. This does not involve os.walk, it's not for the local file system. It's from a txt file, or list.
Basically trying to find something similar to the os.walk output, but bring the information in from a list or file, rather than the local system. Any ideas or direction for this?
Upvotes: 0
Views: 376
Reputation: 4401
you can solve this with some logic
with open('filename.txt') as in_file:
for line in in_file.readlines():
as_list = line.split('/')
# special case for the root
if len(as_list) == 2 and as_list[0] == '' and as_list[-1] == '\n':
indent = 0
else:
indent = (len(as_list) - 1) * 4 + len(as_list[-1]) + 1
output = '/{}'.format(as_list[-1].strip('\n'))
print(output.rjust(indent))
Upvotes: 0