python遍历目录下的文件或目录


#方法1:使用os.listdir

import os
for filename in os.listdir(r'c:\windows'):
    print filename

#方法2:使用glob模块,可以设置文件过滤

import glob
for filename in glob.glob(r'c:\windows\*.exe'):
    print filename

#方法3:通过os.path.walk递归遍历,可以访问子文件夹

import os.path
def processDirectory ( args, dirname, filenames ):
    print 'Directory',dirname
    for filename in filenames:
        print ' File',filename
os.path.walk(r'c:\windows', processDirectory, None )

#方法4:非递归

import os
for dirpath, dirnames, filenames in os.walk('c:\\winnt'):
    print 'Directory', dirpath
    for filename in filenames:
        print ' File', filename
普人特福的博客cnzz&51la for wordpress,cnzz for wordpress,51la for wordpress