[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:

 

你可能感兴趣的:(python)