写程序我们经常会遇到需要遍历某一个目录下的所有文件这个操作,然而python有现成的库,只需要2个循环就可以搞定。
1 import os 2 3 def all_path(dirname): 4 5 result = []#所有的文件 6 7 for maindir, subdir, file_name_list in os.walk(dirname): 8 9 print("1:",maindir) #当前主目录 10 print("2:",subdir) #当前主目录下的所有目录 11 print("3:",file_name_list) #当前主目录下的所有文件 12 13 for filename in file_name_list: 14 apath = os.path.join(maindir, filename)#合并成一个完整路径 15 result.append(apath) 16 17 return result 18 19 print(all_path("E:\myTest"))
程序运行结果如下:
[‘E:\myTest\kuang3.png’, ‘E:\myTest\txt1.txt’, ‘E:\myTest\txt2.txt’, ‘E:\myTest\YYGB1.png’, ‘E:\myTest\YYGB2.png’, ‘E:\myTest\test1\txt11.txt’, ‘E:\myTest\test2\txt21.txt’, ‘E:\myTest\test2\txt22.txt’ ]
当然现在我们是获取了所有的文件,如果我们只想要某一个类型的文件,那么也很简单,写个过滤就好了。所以修改后的代码如下:
import os
filter=[".txt"] #设置过滤后的文件类型 当然可以设置多个类型
def all_path(dirname):
result = []#所有的文件
for maindir, subdir, file_name_list in os.walk(dirname):
# print("1:",maindir) #当前主目录
# print("2:",subdir) #当前主目录下的所有目录
# print("3:",file_name_list) #当前主目录下的所有文件
for filename in file_name_list:
apath = os.path.join(maindir, filename)#合并成一个完整路径
ext = os.path.splitext(apath)[1] # 获取文件后缀 [0]获取的是除了文件名以外的内容
if ext in filter:
result.append(apath)
return result
print(all_path(“E:\myTest”))
#运行结果
#[‘E:\myTest\txt1.txt’, ‘E:\myTest\txt2.txt’, ‘E:\myTest\test1\txt11.txt’, ‘E:\myTest\test2\txt21.txt’, ‘E:\myTest\test2\txt22.txt’]
或者
def list_files(self, path):
files = []
list_dir = os.walk(path)
for maindir, subdir, all_file in list_dir:
for filename in all_file:
apath = os.path.join(maindir, filename)
if apath.endswith('.txt'):
files.append(apath)