0

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?

7
  • Do the paths in the list end with a/? Commented May 7, 2019 at 8:34
  • Possible duplicate of List directory tree structure in python? Commented May 7, 2019 at 10:02
  • @Georgy, not a dupe as the input here is a textfile, not an actual filesystem Commented May 7, 2019 at 10:46
  • @EdoAkse What do you mean by "actual filesystem"? Commented May 7, 2019 at 10:54
  • In any case, the answer to the OP's question is no, there is no built-in functionality in Python to represent a list of filepaths in a tree-like format. So, they have to write some code. Commented May 7, 2019 at 10:59

1 Answer 1

0

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))

Sign up to request clarification or add additional context in comments.

1 Comment

This worked very well, with the exact output I had in mind. Was making numerous failed attempts at it though. Thank you for adding this in.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.