python遍历单层文件夹的所有文件、遍历包含自文件夹下的所有文件、文件后缀筛选

xiaoxiao2021-02-28  39

只是随笔备忘

单层文件夹

def fun(path): #单层文件夹 for filename in os.listdir(path): if not os.path.isdir(os.path.join(path,filename)):#去掉的话会有文件夹的目录被打印 print (os.path.join(path,filename))

文件夹及其子文件夹的所有文件

def fun(path): #含子文件夹 for (root, dirs, files) in os.walk(path): for filename in files: print(os.path.join(root,filename))

单层加筛选

def fun(path): #单层文件夹 Const_Image_Format = [".jpg",".jpeg",".bmp",".png"]#需要筛出来的文件后缀 for filename in os.listdir(path): if os.path.splitext(filename)[1] in Const_Image_Format : #if not os.path.isdir(os.path.join(path,filename)):#有了后缀判断,因文件夹没后缀这个判断就多余了 print (os.path.join(path,filename))

全层加筛选

def fun(path): #含子文件夹 Const_Image_Format = [".jpg",".jpeg",".bmp",".png"]#1~~~~ for (root, dirs, files) in os.walk(path): for filename in files: if os.path.splitext(filename)[1] in Const_Image_Format :#2~~~~ print(os.path.join(root,filename))

试验台子~~方便试用~~~

import os path=r'D:\pictures'#改在你想遍历的地方 #函数填上面的空行就行了 fun(path)#执行。
转载请注明原文地址: https://www.6miu.com/read-2623598.html

最新回复(0)