LoginSignup
10
11

More than 5 years have passed since last update.

[python] ファイルツリーをさくっと書けるクラスを作ってみた

Posted at

実際のファイルツリーを書くのではなくて、ファイルツリーっぽい文字を書きたい時用。
例えばQiitaに投稿する記事にファイルツリーを書きたいけど、実際のファイルツリーだと余計な情報も入るので、
必要に応じてファイルやフォルダ数を制限したものを書きたい時に使う。
一番下にソースコード

使い方 (概要)

適当にファイル作ってimportしてから使う。

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)
結果
root/
  |__ Applications/
  |__ usr/
        |__ username/
              |__ Documents/
              |     |_  document.pdf
              |__ Downloads/
              |__ Music/
              |__ Picures/
                    |_  icon.svg
                    |_  Images.png

もちろん途中から表示することもできる。

print(home)
結果
username/
  |__ Documents/
  |     |_  document.pdf
  |__ Downloads/
  |__ Music/
  |__ Picures/
        |_  icon.svg
        |_  Images.png

使い方

まず、一番の大本のディレクトリを作る。引数はディレクトリ名。
ここでpop=Falseとすると後のmkdir,touch時の自動printを抑制できる。
defaultはpop=True

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

フォルダを作りたかったらmkdirする。ファイルを作りたかったらtouchする。

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

ディレクトリ移動はcdを使う(1つずつしか移動できない)

usr = root.cd('usr')

あとは同じようにmkdir, touchをしていく。

usr.mkdir('home')

最後に表示したいディレクトリインスタンスでプリントする。

print(root)

以上。

コード

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
10
11
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
10
11