python 中 os.walk() 函數(shù)詳解
os.walk()是一種遍歷目錄數(shù)的函數(shù),它以一種深度優(yōu)先的策略(depth-first)訪問指定的目錄。
其返回的是(root,dirs, files),
- root代表當(dāng)前遍歷的目錄路徑,string類型
- dirs代表root路徑下的所有子目錄名稱,list類型,列表中的每個元素是string類型,代表子目錄名稱。
- files代表root路徑下的所有子文件名稱,返回list類型,列表中的每個元素是string類型,代表子文件名稱。
加入我當(dāng)前的目錄如下。
可以先打印一下其是怎么遍歷的:
import os from os.path import join home_path = "/home" for (root, dirs, files) in os.walk(home_path): print(root) print(dirs) print(files) print("=" * 50)
輸出如下:
/home
['root', 'zhang', 'li']
['test.txt', 'hai.mp4']
==================================================
/home/root
[]
['1.txt', '2.txt', '3.txt']
==================================================
/hoome/zhang
[]
['zhang_1.mp4', 'zhang_2.mp4', 'zhang_3.mp4']
==================================================
/home/li
[]
[]
==================================================
一共三行,
第1行代表當(dāng)前遍歷的目錄,我們稱為root目錄,
第2行代表root目錄下的子目錄列表,我們稱為dirs,
第3行代表root目錄下的子文件列表,我們稱為files,
上面的列表為空就代表當(dāng)前遍歷的root目錄下沒有子目錄或者沒有子文件。
另外,如果我想遍歷home目錄下所有的目錄和文件的絕對路徑,則直接用os.path.join()方法對 子目錄或子文件名 和 root目錄 進(jìn)行拼接即可,則代碼如下:
import os from os.path import join home_path = "/home" for (root, dirs, files) in os.walk(home_path): for dir in dirs: print(join(root, dir)) for file in files: print(join(root, file))
輸出:
/home
/home/root
/home/zhang
/home/li
/home/test.txt
/home/hai.mp4
/home/root/1.txt
/home/root/2.txt
/home/root/3.txt
/home/zhang/zhang_1.mp4
/home/zhang/zhang_2.mp4
/home/zhang/zhang_3.mp4
到此這篇關(guān)于python 中 os.walk() 函數(shù)的文章就介紹到這了,更多相關(guān)python os.walk() 函數(shù)內(nèi)容請搜索本站以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持本站!
版權(quán)聲明:本站文章來源標(biāo)注為YINGSOO的內(nèi)容版權(quán)均為本站所有,歡迎引用、轉(zhuǎn)載,請保持原文完整并注明來源及原文鏈接。禁止復(fù)制或仿造本網(wǎng)站,禁止在非www.sddonglingsh.com所屬的服務(wù)器上建立鏡像,否則將依法追究法律責(zé)任。本站部分內(nèi)容來源于網(wǎng)友推薦、互聯(lián)網(wǎng)收集整理而來,僅供學(xué)習(xí)參考,不代表本站立場,如有內(nèi)容涉嫌侵權(quán),請聯(lián)系alex-e#qq.com處理。