import os
path="d:\\python37" filetype=".pdf" #遍历包括子文件夹 def get_filename(path,filetype): filetype1=filetype.upper() #print(filetype) name =[] final_name = [] for root,dirs,files in os.walk(path): for i in files: #print(i) if i.endswith(filetype) or i.endswith(filetype1): final_name.append(i) return final_name #遍历当前文件夹,不包括子文件夹 def get_filenamea(path,filetype): filetype1=filetype.upper() #print(filetype) name =[] final_name = [] for files in os.listdir(path): if files.endswith(filetype) or files.endswith(filetype1): final_name.append(files) return final_name print(get_filenamea(path,filetype)) print(get_filename(path,filetype))
['daan.pdf', 'dianhua.pdf', 'dianhua1.pdf']
['daan.pdf', 'dianhua.pdf', 'dianhua1.pdf', 'back.pdf', 'filesave.pdf', 'forward.pdf', 'hand.pdf', 'help.pdf', 'home.pdf', 'matplotlib.pdf', 'move.pdf', 'qt4_editor_options.pdf', 'subplots.pdf', 'zoom_to_rect.pdf']