查找目录内指定文件

#导入OS模块
import os
import re
#待搜索的目录路径
path = "Day1-homework"
#待搜索的名称
filename = "2020"
#定义保存结果的数组
result = []
i=0
def findfiles():
    #在这里写下您的查找文件代码吧!
    for root,dirs,filelist in os.walk(path):       
        for f in filelist:
            if re.search(filename,f):  #此处也可考虑使用if f in filename:格式方法,而不必导入re模块
                global i
                apath=os.path.join(root,f)
                result.append(apath)                                              
                print("[{0},'{1}']".format(i,result[i]))
                i+=1  
              

if __name__ == '__main__':
    findfiles()

'''
#更简单的方法,来查询names里有没有superman
if 'superman' in names:
    print('有超人')
else:
    print('有超人')
'''
 

也可以不使用,re模块进行比对。

不用re模块比对的后续再补上。

下图是网友的(参考):

原文地址:https://www.cnblogs.com/Li-JT/p/12888727.html