查找當(dāng)前目錄內(nèi),包含所輸入關(guān)鍵字的txt文件,并標(biāo)注出,是在文件的第幾行,和第幾個(gè)位置
from os import walk,getcwd
from os.path import join
def search_file():
'''
查找當(dāng)前目錄底下的所有文件资铡!
return返回的結(jié)果為列表:‘/路徑/文件.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):
'''
傳入兩個(gè)參數(shù),文件名,要查找字符串
查找匹配字符串的行
生成結(jié)果以字典形式返回
如果文件沒有匹配字符串的行,返回空字典
: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
接收用戶輸入是否確認(rèn)查詢daying
確認(rèn)查詢幢码,返回查詢結(jié)果
確認(rèn)不查詢笤休,退出程序
: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 + ']' + "中找到關(guān)鍵字" + '[' + zfc + ']')
for each_key in result.keys():
print('關(guān)鍵字出現(xiàn)在第' + str(each_key) + '行,第' + str(result[each_key]) + '個(gè)位置!')
else:
print('退出查詢!')
zfc = input('請(qǐng)將該腳本放于待查找的文件夾內(nèi)症副,請(qǐng)輸入關(guān)鍵字:').strip()
daying = input('請(qǐng)問是否打印關(guān)鍵字' + zfc + '在文件中的具體位置(YES/NO):').strip()
zfc_line_weizhi(zfc,daying)