python os模組 生成目錄樹

2021-10-05 22:31:15 字數 1161 閱讀 6147

**:

import os

deflist_file

(start_path)

:for root, subdirs, files in os.walk(start_path)

:# root.subdirs,files分別是父路徑,子目錄列表,子檔案列表

level = root.replace(start_path,'')

.count(os.sep)

dir_indent =

'| '

* level +

'|--'

file_indent =

'| '

*(level +1)

+'|--'

if level:

print

('{}{}'

.format

(dir_indent, os.path.basename(root)))

else

:print

('{}'

.format

(start_path[0]

))print

('{}{}'

.format

('|--'

, start_path[3:

]))for f in files:

print

('{}{}'

.format

(file_indent, f)

)start_path = r'c:\users\xjq\music\aa'

list_file(start_path)

執行結果:

c|-

-users\xjq\music\aa||

--新建 docx 文件.docx||

--新建 ppt 演示文稿.ppt||

--新建 rtf 文件.rtf||

--cc||

|--001.txt||

|--新建文字文件.txt||

--新建資料夾||

|--cc|||

|--001.txt||

--新建資料夾 (2)

|||-

-cc|||

|--001.txt||

|--新建資料夾

python os模組 遍歷目錄

1 os 2 os tree命令 3importos4 56 遞迴 7 目錄 檔案,資料夾 檔案資料夾 8 dirpath input 請輸入你要遍歷的目錄 n 9def getdir dirpath,level 0 10 level 1 遞迴的深度 11if notdirpath 12 dirpa...

python os介紹 Python os模組介紹

os模組主要用於執行系統命令 import os os.remname file.txt file1.txt 檔案重新命名 os.remove file1.txt 刪除檔案 os.mkdir test 建立資料夾 os.rmdir test 刪除資料夾 os.sep 可以取代作業系統特定的路徑分割符...

關於Python OS模組常用檔案 目錄函式詳解

模組 包含定義函式和變數的python檔案,可以被別的程式引入。os模組是作業系統介面模組,提供nmszdbtktt了一些方便使用作業系統相關功能函式,這裡介紹下os模組中對於檔案 目錄常用函式和使用方法。1.返回當前檔案目錄 getcwd 2.改變工作目錄 chdir path 將當前工作目錄更改...