0

textfile I want to print the data from a text file in a tree structure.

consider two lines from a text file :

  1. dsin100days/content/Python_for_Data_Scientists/Introduction_to_Python/python-basics.ipynb
  2. dsin100days/content/Python_for_Data_Scientists/hello_world.txt

The output should be:

dsin100days
     content
          Python_for_Data_Scientists
              Introduction_to_Python
                  python-basics.ipynb
             hellow_world.txt

By this we can print all lines but how can i give them a structure. As i am newbie i did not understand how to do it.

with open('sample.txt') as dd:
for record in dd:
    print(record)
Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
Dev
  • 31
  • 5

2 Answers2

0

Import os in your program and go through os.walk(yourPath)

You can refer below link :

List directory tree structure in python?

Pankaj_Dwivedi
  • 565
  • 4
  • 15
  • But i need to use the data from the text file how can i do that...Please elaborate – Dev Feb 12 '20 at 13:46
0
#!/usr/bin/env python3
import re
import json

data_file = 'data.txt'

def main():
    structure = {}
    try:
        with open(data_file) as data_fh:
            for string in data_fh:
                structure = structure_adder(string.split("/"), structure)
    except IOError:
        print("File not accessible")

    structure_printer(structure, 0)
    #print(json.dumps(structure, indent=4))

def structure_printer(structure, tabs):
    for item in structure:
        print ("{}{}".format("    "*tabs, item))
        if structure[item]:
            structure_printer(structure[item], tabs+1)

def structure_adder(items, structure):
    if items:
        item = items.pop(0).replace('\n', '')

        if not item:
            return structure
        if not item in structure:
            structure[item] = {}

        structure[item] = structure_adder(items, structure[item])

    return structure

if __name__ == '__main__':
    main()
fzeulf
  • 1
  • 2
  • For deep folders recursion will throw RunTime Error "maximum recursion depth exceeded" . – Pankaj_Dwivedi Feb 12 '20 at 13:58
  • I am not getting data as above i mentioned...Did you tried to run that file – Dev Feb 12 '20 at 14:00
  • Yep, I know about depth limit of recursion, it could be increased. For small task it is ok. Dev, l've checked with your data, it printed. What do u mean not getting? Empty print or bad formatting? Try to run code in the debug, may be u found what is wrong – fzeulf Feb 12 '20 at 14:52
  • I will check Big file tomorrow, sorry miss the link – fzeulf Feb 12 '20 at 14:59
  • @Dev check plz, i've changed code, image with result https://clip2net.com/s/45YJdSx – fzeulf Feb 13 '20 at 09:25