查找当前目录内,包含所输入关键字的txt文件,并标注出,是在文件的第几行,和第几个位置
from os import walk,getcwd
from os.path import join
def search_file():
'''
查找当前目录底下的所有文件!
return返回的结果为列表:‘/路径/文件.txt’
'''
file_list=[]
for each_dir_file in walk(getcwd()):
if each_dir_file[2] != []:
for each_file in each_dir_file[2]:
if each_file[-4:] == '.txt':
temppath=join(each_dir_file[0],each_file)
file_list.append(temppath)
return file_list
def chazhao(filename,zfc):
'''
传入两个参数,文件名,要查找字符串
查找匹配字符串的行
生成结果以字典形式返回
如果文件没有匹配字符串的行,返回空字典
:param filename:
:param zfc:
:return:
'''
count1 = 0
dict_line_weizhi = {}
file = open(filename)
for each_line in file:
count1 += 1
if zfc in each_line:
weizhi=[]
begin_zfc = each_line.find(zfc)
while begin_zfc != -1:
weizhi.append(begin_zfc)
begin_zfc = each_line.find(zfc, begin_zfc + 1)
dict_line_weizhi.setdefault(count1,weizhi)
else:
dict_line_weizhi={}
file.close()
return dict_line_weizhi
def zfc_line_weizhi(zfc,daying):
'''
接收用户输入需要查找的字符串zfc
接收用户输入是否确认查询daying
确认查询,返回查询结果
确认不查询,退出程序
:param zfc:
:param daying:
:return:
'''
if (daying == 'YES') or (daying == 'yes') or (daying == 'Yes'):
file_list = search_file()
for each_file in file_list:
result = chazhao(each_file, zfc)
if result != {}:
print('在文件' + '[' + each_file + ']' + "中找到关键字" + '[' + zfc + ']')
for each_key in result.keys():
print('关键字出现在第' + str(each_key) + '行,第' + str(result[each_key]) + '个位置!')
else:
print('退出查询!')
zfc = input('请将该脚本放于待查找的文件夹内,请输入关键字:').strip()
daying = input('请问是否打印关键字' + zfc + '在文件中的具体位置(YES/NO):').strip()
zfc_line_weizhi(zfc,daying)