利用Python的os.walk()方法對文件目錄進行歷遍操作,得到文件目錄信息,方便下一步操作 ...
Automate the Boring Stuff 學習筆記 01
使用 os 模塊的 walk() 函數可以實現歷遍目錄的操作,該函數接收一個絕對路徑字元串作為必選參數,返回三個參數:
- 當前目錄——指程式當前工作目錄——名稱(字元串格式)
- 當前目錄——指程式當前所歷遍到的目錄——下所有子文件夾(列表格式)
- 當前目錄——指程式當前所歷遍到的目錄——下所有文件(列表格式)
假設有如下文件結構:
程式代碼如下:
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(”)
程式輸出結果為:
The current folder is C:\delicious
SUBFOLDER OF C:\delicious: cats
SUBFOLDER OF C:\delicious: walnut
FILE INSIDE C:\delicious: spam.txtThe current folder is C:\delicious\cats
FILE INSIDE C:\delicious\cats: catnames.txt
FILE INSIDE C:\delicious\cats: zophie.jpgThe current folder is C:\delicious\walnut
SUBFOLDER OF C:\delicious\walnut: wafflesThe current folder is C:\delicious\walnut\waffles
FILE INSIDE C:\delicious\walnut\waffles: butter.txt.