python os模組 遍歷目錄

2022-05-24 16:03:10 字數 764 閱讀 2409

1#os

2#os ->tree命令

3importos4

56#遞迴

7#目錄 ->檔案,資料夾 -> 檔案資料夾

8 dirpath = input('

請輸入你要遍歷的目錄\n')

9def getdir(dirpath,level =0):

10 level += 1#

遞迴的深度

11if

notdirpath:

12 dirpath =os.getcwd()

1314

#預設情況從當前路徑開始

15 mylist=os.listdir(dirpath)16#

取出來所有檔案和資料夾17#

os.path.isdir() 判斷檔案是否是路徑

18for name in

mylist:

19print('

--' * level +'

∟'+name)20#

這裡只是乙個相對路徑

21 name =os.path.join(dirpath,name)

22if

os.path.isdir(name):

23 getdir(name,level)#

這裡使用遞迴呼叫,因為如果不是檔案的話 就繼續呼叫getdir(),

2425

getdir(dirpath)

26

python os模組 生成目錄樹

import os deflist file start path for root,subdirs,files in os.walk start path root.subdirs,files分別是父路徑,子目錄列表,子檔案列表 level root.replace start path,coun...

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 將當前工作目錄更改...