Home > Net >  How to recursively print my directory structure with indentations? (no imported modules)
How to recursively print my directory structure with indentations? (no imported modules)

Time:11-30

So I have created a directory structure from scratch. I am pretty new to python. This is my code

class File:
    def __init__(self, name, contents = [], owner = "No owner currently defined"):
        self.name = name
        self.contents = contents
        self.owner = owner
    
    def CreateOwner(self, new_owner):
        self.owner = new_owner


class Directory(File):
    def __repr__(self):
        return f"Directory({self.name}, {self.contents})"
    

        
            
class PlainFile(File):
    def __init__(self, name, owner = "No owner currently defined"):
        self.name = name
        self.owner = owner
   

I have made this directory structure

root = Directory("root",
                 [PlainFile("boot.exe"), 
                 Directory("home", [
                     Directory("Julius",
                               [PlainFile("dog.jpg"),
                                PlainFile("homework.txt")]), 
                     Directory("Cameron", [PlainFile("Elephant.jpg")])])])

And I want to make a function that will recursively print the names of each directory with their subdirectories and files directly underneath them but indented to the right to show that they come from the certain directory. And so each time a new directory is opened from within a directory a new indent is made. I really don't know how to. I have tried for loops and while loops but can't get it to work, I don't even know how to make indentations for opening new directories. Please help :(

CodePudding user response:

Welcome to the world of python and stackoverflow! Good news is that the solution to your problem is very straight-forward. First off, some quick but important comments on your working code:

  • contents: should probably only be an attribute of the Directory subclass. Also, enter image description here

    Turning the function into a Directory method is something I'll leave as an exercise to the reader. Hint:

    One way of doing this is to have 2 seperate methods with the one being used from the outside being a shortcut using the current instance to the main method with the main logic which isn't instance-bound. Bonus points if making the latter a classmethod.

    Try now and see if it goes better. Comment here if you get stuck again. I have coded a solution which works, but trying yourself first is always better for understanding.

    CodePudding user response:

    Hopefully you are comfortable with recursion. Just some sample code, so that you can build up. For eg I have not used your repr overload, you can do that easily.

    (On a diff note, In your code , you are inheriting from File for directory/Plain file class , but are not calling parent constructor. Some clean up there, and you can simplify this code too)

    def rec_print (file_obj:File,level):
        try:
            if file_obj.contents:
                pass
        except Exception as e:
            return
    
        for obj in file_obj.contents:
            indents = "".join(["\t" for idx in range(level)])
            print( f"{indents }{obj.name}")
            rec_print(obj, level 1)
    
  • Related