[python] I made a class that can write a file tree quickly

For when you want to write file tree-like characters instead of writing the actual file tree. For example, I want to write a file tree in an article posted on Qiita, but if it is an actual file tree, extra information will be included, so Use when you want to write a limited number of files and folders as needed. Source code at the bottom

How to use (overview)

Create a file and import it before using it.

from filename import directory

root = directory('root')
root.mkdir('usr')
root.mkdir('Applications')
usr = root.cd('usr')
usr.mkdir('username')
home = usr.cd('username')
home.mkdir('Documents')
home.mkdir('Music')
home.mkdir('Downloads')
doc = home.cd('Documents')
doc.touch('document.pdf')
home.mkdir('Picures')
pic = home.cd('Picures')
pic.touch('Images.png')
pic.touch('icon.svg')

print(root)

result


root/
  |__ Applications/
  |__ usr/
        |__ username/
              |__ Documents/
              |     |_  document.pdf
              |__ Downloads/
              |__ Music/
              |__ Picures/
                    |_  icon.svg
                    |_  Images.png

Of course, it can be displayed from the middle.

print(home)

result


username/
  |__ Documents/
  |     |_  document.pdf
  |__ Downloads/
  |__ Music/
  |__ Picures/
        |_  icon.svg
        |_  Images.png

How to use

First, create the best directory. The argument is the directory name. If pop = False here, automatic print at the time of mkdir and touch can be suppressed later. default is pop = True

root = directory('root',pop=False)

If you want to create a folder, mkdir. If you want to create a file, touch it.

root.mkdir('usr')
root.mkdir('Applications')
root.touch('config')

Use cd to move directories (only one can be moved)

usr = root.cd('usr')

After that, do mkdir and touch in the same way.

usr.mkdir('home')

Print in the directory instance you want to display last.

print(root)

that's all.

code

filetree


class directory:
    def __init__(self,name,parent=None,pop=True):
        self.name = name
        self.parent = parent
        self.childs = []
        self.files = []
        self.pop = pop

    def mkdir(self,name):
        if name in map(lambda x:x.name,self.childs):
            print('this directory have same name')
        else:
            self.childs.append(directory(name,self))
        self.childs.sort(key=lambda x:x.name.lower())
        if self.pop:
            if self.parent:
                print(self.parent.__str__())
            else:
                print(self.__str__())

    def cd(self,name):
        for i in self.childs:
            if i.name == name:
                return i
        raise IndexError(name)

    def touch(self,name):
        if name in self.files:
            print('this directory have same name')
        else:
            self.files.append(name)
        self.files.sort(key=str.lower)
        if self.pop:
            if self.parent:
                print(self.parent.__str__())
            else:
                print(self.__str__())

    def __str__(self):
        word = ''
        word += self.name
        word += '/\n'
        for i in range(len(self.childs)):
            addlines = '  |__ '
            addlines += self.childs[i].__str__()
            addlines = addlines.splitlines()
            word += addlines[0]
            word += '\n'
            if self.files or i+1 < len(self.childs):
                word += '\n'.join(map(lambda x: '  |   ' + x,addlines[1:]))
            else:
                word += '\n'.join(map(lambda x: '      ' + x,addlines[1:]))
            if self.childs[i].childs or self.childs[i].files:
                word += '\n'
        for j in self.files:
            word += '  |_  '
            word += j
            word += '\n'
        return word

Recommended Posts

[python] I made a class that can write a file tree quickly
I made a configuration file with Python
I made a package that can compare morphological analyzers with Python
I made a shuffle that can be reset (reverted) with Python
I made a library that adds docstring to a Python stub file.
I made a python dictionary file for Neocomplete
I want to write to a file with Python
[Python] I made a utility that can access dict type like a path
I made a module PyNanaco that can charge nanaco credit with python
I tried to create a class that can easily serialize Json in Python
I made a Christmas tree lighting game with Python
I made a VM that runs OpenCV for Python
I made a Docker image that can call FBX SDK Python from Node.js
I made a familiar function that can be used in statistics with Python
I made a python text
I made a class that easily performs unixtime ← → datetime conversion
I made a plug-in that can "Daruma-san fell" with Minecraft
How to write a Python class
I made a Line-bot using Python!
I made a fortune with Python.
I made a daemon with Python
[Python] I made a Line bot that randomly asks English words.
[Python3] I made a decorator that declares undefined functions and methods.
I made a segment tree with python, so I will introduce it
How can I write a good program?
I made a character counter with Python
I made a Hex map with Python
After studying Python3, I made a Slackbot
I made a roguelike game with Python
I made a simple blackjack with Python
I made a neuron simulator with Python
I created a template for a Python project that can be used universally
[Python] I made a decorator that doesn't seem to have any use.
I made a web application in Python that converts Markdown to HTML
I made a Discord bot in Python that translates when it reacts
I made a tool that makes decompression a little easier with CLI (Python3)
[IOS] I made a widget that displays Qiita trends in Pythonista3. [Python]
I made a program to check the size of a file in Python
[Python] I made a function that can also use regular expressions that replace character strings all at once.
I made a competitive programming glossary with Python
A memo that I wrote a quicksort in Python
I made a GUI application with Python + PyQt5
[Python / Tkinter] A class that creates a scrollable Frame
I made a Twitter fujoshi blocker with Python ①
I wrote a class in Python3 and Java
[Python] I made a Youtube Downloader with Tkinter.
I tried reading a CSV file using Python
Python: Create a class that supports unpacked assignment
I made a Caesar cryptographic program in Python.
I made a bin picking game with Python
I made a Mattermost bot with Python (+ Flask)
I made a Python Qiita API wrapper "qiipy"
A class for PYTHON that can be operated without being aware of LDAP
From a book that programmers can learn (Python): Class declaration (public / private, etc.)
I want to create a priority queue that can be updated in Python (2.7)
I registered PyQCheck, a library that can perform QuickCheck with Python, in PyPI.
[Beginner] What happens if I write a program that runs in php in Python?
[Python] I made a LINE Bot that detects faces and performs mosaic processing.
In Python, I made a LINE Bot that sends pollen information from location information.
A story that I was addicted to when I made SFTP communication with python
I made a tool in Python that right-clicks an Excel file and divides it into files for each sheet.