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