Skip to content

Instantly share code, notes, and snippets.

@xin053
Last active July 4, 2019 07:50
Show Gist options
  • Save xin053/9bd1f8c942e113635eb076168714d67a to your computer and use it in GitHub Desktop.
Save xin053/9bd1f8c942e113635eb076168714d67a to your computer and use it in GitHub Desktop.
[python 遍历文件]遍历目录下所有文件 #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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment