|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
- def search_file(start_dir,target): #建立一个搜索指定格式文件的模块
- os.chdir(start_dir)
- for each_file in os.listdir(start_dir):
- ext = os.path.splitext(each_file)[1]
- if ext in target:
- text_file.append(os.getcwd + os.sep + each_file) #该列表内含有的均为路径
- if os.path.isdir(each_file):
- search_file(start_dir,target) #递归调用
- os.chdir(os.pardir)
- def search_right_file(text_file): #筛选出含有关键字的文件
- choice_file = []
- for each_file in text_file:
- choice_file.append(open(each_file,'r'))
- if keyword in choice_file:
- print('在文件【',each_file,'】中找到关键字【',keyword,'】')
- if judge_print == 'yes': #显示关键字在文件中的具体位置
- count_line = 1
- count_colunm = []
- for each_line in choice_file:
- if keyword in each_line:
- for i in len(each_line):
- if each_line[i] == 'keyword[0]' and each_line[i+1] == 'keyword[1]':
- count_colunm,append(i)
- print('关键字出现在第',count_line,'行,','第',count_colunm,'个位置')
- count_line +=1
- count_colunm = []
- choice_file = []
- else:
- text_file.remove(each_file)
- choice_file = []
- continue
- import os
- target = ['txt']
- text_file = []
- start_dir = input('请输入待查找的初始目录:')
- keyword = input('请输入关键词:')
- judge_print = input('请问是否需要打印关键字在文件中的具体位置(yes/no):')
- search_file(start_dir,target)
- search_right_file(text_file)
复制代码
运行后我也不知道是什么错误,求解答! |
-
|