LoginSignup
1
0

More than 5 years have passed since last update.

treeコマンドもどきをpythonで書いてみた

Last updated at Posted at 2017-09-16

はじめに

WindowsのtreeコマンドみたいなものがLinux環境で使えれば良いなと思い調べてみたが、
どうやら標準コマンドではないらしい。

これでは手軽に tree をインストール出来ない環境だと使えない・・・と思ったので
pythonで実装してみることにした。

treeコマンドの実行例(DOSコマンドの場合)

N:.
├─Document
│  ├─Backup
│  └─Download Files
├─Pictures
├─Video
└─Work
    ├─2010
    |  └─Event
    ├─2011
    └─2012

ソースコード

walk関数を使ってカレントディレクトリ直下のディレクトリ・ファイルを取得。
ファイル構造が変わった時にdiffが取れるように
出力結果はtxtファイルに出力できるようにした。

tree.py
# -*- coding: utf-8 -*-

import os

#export file
exportfile = "filetree.txt"

#current directory
searchdir = "."

print ("Export Start!")
wk = os.walk(searchdir)
with open(exportfile,mode="w") as f:
    for dirpath, dirs, files in wk:
        path = dirpath.split("/") 
        f.write("\t"*(len(path)-2) + path[-1] + "\n")
        for x in files:
            f.write("\t"*(len(path)-1) + "|" + "-" + x + "\n")
print ("Export Finished!")

出力結果

出力先のディレクトリ構造を下記とする。
1〜10の名前のついたディレクトリの中に、
それぞれ"11.txt"と"12.txt"の2つのテキストファイルが入っている。

スクリーンショット 2017-09-16 18.49.35.png

出力結果はこちら
スクリーンショット 2017-09-16 19.01.12.png

全てのファイルを取得することには成功したが見た目がまだ微妙。
DOSのtreeコマンドみたいに見た目をもう少し改善したいところ・・・!

1
0
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
1
0