[work] python 文件夾遍歷

Last Updated: Wednesday 14th August 2013

When you use a scripting language like Python, one thing you will find yourself doing over and over again is walking a directory tree, and processing files. While there are many ways to do this, Python offers a built-in function that makes this process a breeze.

Basic Python Directory Traversal

Here's a really simple example that walks a directory tree, printing out the name of each directory and the files contained:

 

1

2

3

4

5

6

7

8

9

# Import the os module, for the os.walk function

import os

 

# Set the directory you want to start from

rootDir = '.'

for dirName, subdirList, fileList in os.walk(rootDir):

    print('Found directory: %s' % dirName)

    for fname in fileList:

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章