文章目錄
os.walk()
os.walk
訪問目錄,並返回可以訪問該目標的生成器:
walk(top, topdown=True, onerror=None, followlinks=False)`
Params:
- top:所要遍歷的目錄地址;
- topdown:默認爲真,表示優先遍歷子目錄;
- 其他默認就可以了
- 如果 topdown 參數爲真,
walk
會遍歷top
文件夾,與top
文件夾中每一個子目錄。 os.walk
的返回值是一個生成器(generator),也就是說我們需要不斷的遍歷它,來獲得所需要的內容。每次遍歷的對象都是返回一個三元組(root,dirs,files)
。- root:所指的是當前正在遍歷的這個文件夾的本身的地址。
- dirs:是一個list,內容是該文件夾中所有的目錄的名字(不包括子目錄)。
- files:同樣是一個list,內容是該文件夾所有的文件(不包括子目錄)
例如:
import os
i = 0
for (root, dirs, files) in os.walk("../"):
print("index: ", i)
print("root: ", root)
print("dirs: ", dirs)
print("files: ", files)
i += 1
print("\n")
"""
結果如下:
index: 0
root: ../
dirs: ['b', 'mlclass-ex6-jin', 'ros_dynamixel', 'catkin_ws', 'ros_test']
files: []
index: 1
root: ../b
dirs: ['tcp_cs_thread', 'python_mode', 'C++', 'arithmetic', 'tcp_cs_select', 'udp_cs', 'tcp_cs_fcntl', 'tcp_cs', 'HelloZach', 'tcp_cs_pid']
files: ['setup.py~']
index: 2
root: ../b/tcp_cs_thread
dirs: []
files: ['abc.txt', 'tcp_net_server', 'test.txt', 'tcp_net_client.c', 'tcp_net_client', 'tcp_net_server.c']
...
"""