遍歷目錄樹

2021-10-23 10:23:04 字數 1324 閱讀 8555

cpath = os.getcwd(

)# 如果目錄名字為中文 需要轉碼處理

upath =

unicode

(cpath,

'utf-8'

)for filename in os.listdir(upath)

:print filename

import os 

for foldername, subfolders, filenames in os.walk(

'c:\\delicious'):

print

('the current folder is '

+ foldername)

for subfolder in subfolders:

print

('subfolder of '

+ foldername +

': '

+ subfolder)

for filename in filenames:

print

('file inside '

+ foldername +

': '

+ filename)

print

('\n'

)

os.walk()在迴圈的每次迭代中,返回 3 個值: 1.當前資料夾名稱的字串。 2.當前資料夾中子資料夾的字串的列表。 3.當前資料夾中檔案的字串的列表。

列印結果:

ftw遍歷目錄樹

表頭檔案 include 定義函式 int ftw const char dir,int fn const file,const struct stat sb,int flag int depth 函式說明 ftw 會從引數dir指定的 目錄開始,往下一層層地遞迴式遍歷子 目錄。ftw 會傳三個引數...

nftw遍歷目錄樹

表頭檔案 include 定義函式 int nftw const char dir,int fn const char file,const struct stat sb,int flag,struct ftw s depth,int flags 函式說明 nftw 與ftw 很像,都是從引數dir...

python遍歷目錄樹

假定你希望對某個資料夾中的所有檔案改名,包括該資料夾中所有子資料夾中的所有檔案。也就是說,你希望遍歷目錄樹,處理遇到的每個檔案。寫程式完成這件事,可能需要一些技巧。好在,python 提供了乙個函式,替你處理這個過程。請看 c delicious 資料夾及其內容,如圖 9 1 所示。這裡有乙個例子程...