Output tree structure of files in Python

Overview

I made a function to output the tree structure of files and directories on Python like a tree of commands, so make a note.

Conclusion

Give the following function the path of the directory you want to display in the tree. Since it is implemented for Mac, it is not supported when paths are not separated by slashes.

import pathlib
import glob
import os

def tree(path, layer=0, is_last=False, indent_current=' '):
    if not pathlib.Path(path).is_absolute():
        path = str(pathlib.Path(path).resolve())
    
    #View current directory
    current = path.split('/')[::-1][0]
    if layer == 0:
        print('<'+current+'>')
    else:
        branch = '└' if is_last else '├'
        print('{indent}{branch}<{dirname}>'.format(indent=indent_current, branch=branch, dirname=current))
    
    #Get the path of the lower hierarchy
    paths = [p for p in glob.glob(path+'/*') if os.path.isdir(p) or os.path.isfile(p)]
    def is_last_path(i):
        return i == len(paths)-1
    
    #Display recursively
    for i, p in enumerate(paths):
        
        indent_lower = indent_current
        if layer != 0:
            indent_lower += '  ' if is_last else '│ '
            
        if os.path.isfile(p):
            branch = '└' if is_last_path(i) else '├'
            print('{indent}{branch}{filename}'.format(indent=indent_lower, branch=branch, filename=p.split('/')[::-1][0]))
        if os.path.isdir(p):
            tree(p, layer=layer+1, is_last=is_last_path(i), indent_current=indent_lower)

For example, consider the case where the directory called Test is configured as follows.

When tree is executed at this time, it looks like this.

tree('/hogehoge/Test')

Output result


<Test>
 ├<Test_01>
 │ ├ccccc.txt
 │ └bbbbb.txt
 ├<Test_02>
 ├<Test_03>
 └aaaaa.txt

The result is the same even if you specify it with a relative path.

tree('./') # /hogehoge/Run with Test

Output result


<Test>
 ├<Test_01>
 │ ├ccccc.txt
 │ └bbbbb.txt
 ├<Test_02>
 ├<Test_03>
 └aaaaa.txt

Recommended Posts

Output tree structure of files in Python
Handling of JSON files in Python
Export and output files in Python
C-like structure in Python
Japanese output in Python
Basics of python: Output
Output the number of CPU cores in Python
Summary of how to import files in Python 3
Output in the form of a python array
Speed evaluation of CSV file output in Python
Output table structure in Django
Equivalence of objects in Python
Recursively search for files and directories in Python and output
Implementation of quicksort in Python
Read Fortran output in python
A set of script files that do wordcloud in Python3
Transpose CSV files in Python Part 1
Pixel manipulation of images in Python
Output 2017 Premium Friday list in Python
Division of timedelta in Python 2.7 series
Manipulate files and folders in Python
MySQL-automatic escape of parameters in python
Download Google Drive files in Python
Make standard output non-blocking in Python
Implementation of life game in Python
Waveform display of audio in Python
Compiler in Python: PL / 0 syntax tree
Sort large text files in Python
Read files in parallel with Python
Python implementation of non-recursive Segment Tree
Law of large numbers in python
Implementation of original sorting in Python
Algorithm (segment tree) in Python (practice)
Reversible scrambling of integers in Python
Extract strings from files in Python
How to know the internal structure of an object in Python
Write various forms of phylogenetic tree in Python using ETE Toolkit
Output the contents of ~ .xlsx in the folder to HTML with Python
Read the standard output of a subprocess line by line in Python
Take a look at the built-in exception tree structure in Python 3.8.2
Get a list of files in a folder with python without a path
Conversion of string <-> date (date, datetime) in Python
Data input / output in Python (CSV, JSON)
Check the behavior of destructor in Python
(Bad) practice of using this in Python
General Theory of Relativity in Python: Introduction
Find files like find on linux in Python
Display a list of alphabets in Python 3
Comparison of Japanese conversion module in Python3
Summary of various for statements in Python
Type annotations for Python2 in stub files!
Referencing INI files in Python or Ruby
The result of installing python in Anaconda
Automate jobs by manipulating files in Python
Gang of Four (GoF) Patterns in Python
Basics: Full Search of Tree Structure (DFS/BFS)
Read and write JSON files in Python
The basics of running NoxPlayer in Python
UnicodeEncodeError struggle with standard output of python3
Sample for handling eml files in Python
Bulk replacement of strings in Python arrays