基于Python實現(xiàn)優(yōu)雅的目錄結(jié)構(gòu)打印工具
在軟件開發(fā)、系統(tǒng)管理和日常工作中,我們經(jīng)常需要查看和分析目錄結(jié)構(gòu)。
工具功能概述
這個DirectoryPrinter
類提供了以下功能:
- 遞歸打印目錄結(jié)構(gòu)
- 可配置是否顯示隱藏文件
- 可設(shè)置最大遞歸深度
- 自定義縮進(jìn)和文件/文件夾符號
- 友好的交互式配置界面
核心代碼解析
初始化配置
def __init__(self, root_dir, show_hidden=False, depth=0, max_depth=None, indent_symbol='│ ', folder_symbol='/ ', file_symbol='- '): self.root_dir = root_dir self.show_hidden = show_hidden self.max_depth = max_depth self.indent_symbol = indent_symbol self.folder_symbol = folder_symbol self.file_symbol = file_symbol self.depth = depth
構(gòu)造函數(shù)接收多個參數(shù),允許用戶自定義打印行為。特別是indent_symbol
、folder_symbol
和file_symbol
參數(shù),可以完全改變輸出樣式。
目錄打印邏輯
def print_directory(self): try: items = os.listdir(self.root_dir) except FileNotFoundError: print(f"指定的目錄 {self.root_dir} 不存在") return except PermissionError: print(f"無法訪問目錄 {self.root_dir}") return # 過濾隱藏文件 if not self.show_hidden: items = [item for item in items if not (item.startswith('.') and os.path.isfile(os.path.join(self.root_dir, item)))]
方法首先嘗試列出目錄內(nèi)容,并處理可能出現(xiàn)的異常。然后根據(jù)配置過濾隱藏文件。
遞歸打印
for index, item in enumerate(sorted(items), start=1): path = os.path.join(self.root_dir, item) is_dir = os.path.isdir(path) # 構(gòu)建前綴 prefix = self.indent_symbol * self.depth if index == len(items): if is_dir: print(f"{prefix}└── {self.folder_symbol}{item}") else: print(f"{prefix}└── {self.file_symbol}{item}") else: if is_dir: print(f"{prefix}├── {self.folder_symbol}{item}") else: print(f"{prefix}├── {self.file_symbol}{item}") # 遞歸處理子目錄 if is_dir: child_printer = DirectoryPrinter( root_dir=path, show_hidden=self.show_hidden, depth=self.depth + 1, max_depth=self.max_depth, indent_symbol=self.indent_symbol, folder_symbol=self.folder_symbol, file_symbol=self.file_symbol ) child_printer.print_directory()
這部分代碼實現(xiàn)了遞歸打印的核心邏輯,使用不同的符號區(qū)分文件和文件夾,以及區(qū)分是否是最后一項。
使用示例
通過交互式界面配置打印參數(shù):
def main(): root_directory = input("請輸入要打印的目錄路徑: ") or os.getcwd() hide_hidden_files = input("是否隱藏隱藏文件? (y/n): ").lower() != 'y' max_depth = input("請輸入最大遞歸深度 (留空表示無限制): ").strip() or None auto_print = input("是否自動打印目錄結(jié)構(gòu)? (y/n): ").lower() == 'y' printer = DirectoryPrinter( root_dir=root_directory, show_hidden=hide_hidden_files, max_depth=max_depth ) printer.print_directory()
輸出效果
示例輸出可能如下:
├── / dir1
│ ├── - file1.txt
│ └── / subdir
│ └── - file2.txt
└── / dir2
├── - file3.txt
└── - file4.txt
完整代碼
import os class DirectoryPrinter: def __init__(self, root_dir, show_hidden=False, depth=0, max_depth=None, indent_symbol='│ ', folder_symbol='/ ', file_symbol='- '): """ 初始化目錄打印器 :param root_dir: 指定要打印的目錄路徑 :param show_hidden: 是否打印隱藏文件和文件夾(默認(rèn)為 False) :param depth: 當(dāng)前遞歸深度(內(nèi)部使用,用戶無需設(shè)置) :param max_depth: 最大遞歸深度,None 表示無限制 :param indent_symbol: 縮進(jìn)符號 :param folder_symbol: 文件夾前綴符號 :param file_symbol: 文件前綴符號 """ self.root_dir = root_dir self.show_hidden = show_hidden self.max_depth = max_depth self.indent_symbol = indent_symbol self.folder_symbol = folder_symbol self.file_symbol = file_symbol self.depth = depth def print_directory(self): """ 打印目錄結(jié)構(gòu) """ try: items = os.listdir(self.root_dir) except FileNotFoundError: print(f"指定的目錄 {self.root_dir} 不存在") return except PermissionError: print(f"無法訪問目錄 {self.root_dir}") return # 過濾隱藏文件 if not self.show_hidden: items = [item for item in items if not (item.startswith('.') and os.path.isfile(os.path.join(self.root_dir, item)))] # 遞歸打印目錄和文件 for index, item in enumerate(sorted(items), start=1): path = os.path.join(self.root_dir, item) is_dir = os.path.isdir(path) # 根據(jù)當(dāng)前深度和最大深度決定是否繼續(xù)遞歸 if self.max_depth is not None and self.depth > self.max_depth: continue # 構(gòu)建前綴 prefix = self.indent_symbol * self.depth if index == len(items): if is_dir: print(f"{prefix}└── {self.folder_symbol}{item}") else: print(f"{prefix}└── {self.file_symbol}{item}") else: if is_dir: print(f"{prefix}├── {self.folder_symbol}{item}") else: print(f"{prefix}├── {self.file_symbol}{item}") # 遞歸處理子目錄 if is_dir: child_printer = DirectoryPrinter( root_dir=path, show_hidden=self.show_hidden, depth=self.depth + 1, max_depth=self.max_depth, indent_symbol=self.indent_symbol, folder_symbol=self.folder_symbol, file_symbol=self.file_symbol ) child_printer.print_directory() def main(): """ 主函數(shù),用戶配置入口 """ # 配置參數(shù) root_directory = input("請輸入要打印的目錄路徑: ") or os.getcwd() # 默認(rèn)為當(dāng)前目錄 hide_hidden_files = input("是否隱藏隱藏文件? (y/n): ").lower() != 'y' max_depth = input("請輸入最大遞歸深度 (留空表示無限制): ").strip() or None # 無限制 auto_print = input("是否自動打印目錄結(jié)構(gòu)? (y/n): ").lower() == 'y' # 轉(zhuǎn)換為整數(shù) try: max_depth = int(max_depth) if max_depth else None except ValueError: print("最大遞歸深度必須為整數(shù)") return # 打印配置 print("\n=== 配置 ===") print(f"根目錄: {root_directory}") print(f"隱藏文件和文件夾: {'是' if hide_hidden_files else '否'}") print(f"最大遞歸深度: {'無限制' if max_depth is None else max_depth}") # 初始化打印器 printer = DirectoryPrinter( root_dir=root_directory, show_hidden=hide_hidden_files, max_depth=max_depth ) # 開始打印 if auto_print: print("\n=== 目錄結(jié)構(gòu) ===") printer.print_directory() else: input("\n按下回車鍵開始打印目錄結(jié)構(gòu)...") print("\n=== 目錄結(jié)構(gòu) ===") printer.print_directory() # 程序主入口 if __name__ == "__main__": main()
到此這篇關(guān)于基于Python實現(xiàn)優(yōu)雅的目錄結(jié)構(gòu)打印工具的文章就介紹到這了,更多相關(guān)Python打印目錄結(jié)構(gòu)內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!
相關(guān)文章
python轉(zhuǎn)換wrf輸出的數(shù)據(jù)為網(wǎng)頁可視化json格式
這篇文章主要介紹了python轉(zhuǎn)換wrf輸出的數(shù)據(jù)為網(wǎng)頁可視化json格式,文章圍繞主題展開詳細(xì)的內(nèi)容介紹,具有一定的參考價值,需要的小伙伴可以參考一下2022-09-09python3.3使用tkinter開發(fā)猜數(shù)字游戲示例
這篇文章主要介紹了python3.3使用tkinter開發(fā)猜數(shù)字游戲示例,需要的朋友可以參考下2014-03-03python?matplotlib繪圖過程中設(shè)置線條顏色實戰(zhàn)舉例
Matplotlib是一個用于數(shù)據(jù)可視化和創(chuàng)建交互式圖表的Python庫,下面這篇文章主要給大家介紹了關(guān)于python?matplotlib繪圖過程中設(shè)置線條顏色的相關(guān)資料,文中通過實例代碼介紹的非常詳細(xì),需要的朋友可以參考下2023-05-05