方案 1:利用 glob 模块
import glob
import os
dst_path = 'C:/'
ext_name = '*.txt'
os.chdir( dst_path )
for file in glob.glob( ext_name ):
pass方案 2:利用 os.listdir
import os
dst_path = 'd:/'
ext_name = 'txt'
for file in os.listdir( dst_path ):
if file.endswith( ext_name ):
print( file )方案 3: 利用 os.walk 遍历指定路径下所有文件(含子路径,与方案 1 & 2 有显著差异)
import os
dst_path = 'd:/'
ext_name = 'txt'
for r, d, files in os.walk( dst_path ):
for file in files:
if file.endswith( ext_name ):
print( file )
本文介绍了使用Python的三种方法来遍历指定目录及其子目录下的所有.txt文件。第一种方法利用了glob模块,第二种方法使用了os.listdir,第三种方法则通过os.walk实现了递归遍历。
655

被折叠的 条评论
为什么被折叠?



