# 帮助用户查找文件 # 由于windows自带的文件查找很是垃圾,所以我们自己写了一个查找文件的程序 # 1、用户输入文件的关键字 # 2、用户可以输入一个大概的位置,如果用户不输入,默认为/ # 3、返回查找了多少个文件和找到了相关的文件有多少 import os allfile = [] kwfile = [] def check_exists(dir): if os.path.exists(dir): return True else: print('目录不存在,使用默认目录') global p if os.name == 'nt': p = 'c:\\' elif os.name == 'posix': p = '/' # 功能相关 def check_abs(path): os.chdir(path) return os.path.abspath(path) kw = input('请输入需要查询文件中的关键字[default "network"]:') if kw == '': kw = 'network' p = input('请输入文件的大概位置[default C:|/]:') check_exists(p) def main(path): path = check_abs(path) # 执行函数修改成绝对路径 用户输入./test,cd ./test && pwd dirlist = os.listdir(path) # 列表 = ls -A ./ for i in dirlist: # 循环这个列表,获得目录下面的所有文件 allfile.append(os.path.join(path,i)) # 将文件追加到空列表 allfile 中 if os.path.isdir(os.path.join(path,i)): # 使用isdir来判断是否是目录 main(os.path.join(path,i)) if kw in i: # 使用in来判断是否包含关键字 kwfile.append(os.path.join(path,i)) main(p) for i in kwfile: print(i) print(f'在{len(allfile)}个文件中进行了查找') print(f'共查找到{len(kwfile)}个相关文件')