Python入门3----查找特定名称文件
遍历”Day1-homework”目录下文件;
找到文件名包含“2020”的文件;
将文件名保存到数组result中;
按照序号、文件名分行打印输出。
1 import os 2 #待搜索的目录路径 3 path = "Day1-homework" 4 #待搜索的名称 5 filename = "2020" 6 #定义保存结果的数组 7 result = [] 8 9 def findfiles(files_path, files_list): 10 #查找文件代码 11 files = os.listdir(files_path) 12 for s in files: 13 s_path = os.path.join(files_path, s) 14 if os.path.isdir(s_path): 15 findfiles(s_path, files_list) 16 elif os.path.isfile(s_path) and '2020' in s: 17 #result.append(s_path)
files_list.append(s_path) 18 19 20 if __name__ == '__main__': 21 findfiles(path,result) 22 for i in range(len(result)): 23 print("[{} ,".format(i)+"'"+result[i]+"\']")
输出结果:
[0 ,'Day1-homework/26/26/new2020.txt'] [1 ,'Day1-homework/18/182020.doc'] [2 ,'Day1-homework/4/22/04:22:2020.txt']