Last active
July 4, 2019 07:50
-
-
Save xin053/9bd1f8c942e113635eb076168714d67a to your computer and use it in GitHub Desktop.
[python 遍历文件]遍历目录下所有文件 #python #文件
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#方法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