python如何实现查找特定名称文件
遍历”Day1-homework”目录下文件;
找到文件名包含“2020”的文件;
将文件名保存到数组result中;
按照序号、文件名分行打印输出。
#导入OS模块 import os #待搜索的目录路径 path = "Day1-homework" #待搜索的名称 filename = "2020" #定义保存结果的数组 result = [] def findfiles(files_path, files_list): #查找文件代码 files = os.listdir(files_path) for s in files: s_path = os.path.join(files_path, s) if os.path.isdir(s_path): findfiles(s_path, files_list) elif os.path.isfile(s_path) and '2020' in s: result.append(s_path) if __name__ == '__main__': findfiles(path,result) for i in range(len(result)): print("[{} ,".format(i)+"'"+result[i]+"\']")
[0 ,'Day1-homework/18/182020.doc'] [1 ,'Day1-homework/26/26/new2020.txt'] [2 ,'Day1-homework/4/22/04:22:2020.txt']
你有什么心态,就有什么样的人生。管不好自己的心态,注定你就是个弱者。