Python traverses all files in a single-layer folder, traverses all files contained in a folder, and filters file suffixes

just a memo

single level folder

def fun(path): #Single-layer folder
    for filename in os.listdir(path):
        if not os.path.isdir(os.path.join(path,filename)):#If removed, the directory of the folder will be printed
            print (os.path.join(path,filename))


All files of a folder and its subfolders

def fun(path): #include subfolders
    for (root, dirs, files) in os.walk(path):  
        for filename in files:
             print(os.path.join(root,filename))


Single layer plus screening

def fun(path): #Single-layer folder
    Const_Image_Format = [".jpg",".jpeg",".bmp",".png"]#The file suffix to be filtered out
    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)):#With the suffix judgment, because the folder does not have a suffix, this judgment is redundant
            print (os.path.join(path,filename))


Full layer plus filter

def fun(path): #include subfolders
    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))


Test bench~~easy to try~~~

import them
path=r'D:\pictures'#Change where you want to traverse


#Function fill in the blank line above
fun(path)# execute.

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325847851&siteId=291194637