这个是我修改后的代码,可以实现的,但是有些地方比较乱,供参考
import os
def search_file(start_dir):
os.chdir(start_dir)
for each_file in os.listdir(os.curdir):
if os.path.splitext(each_file)[1] == '.txt':#查找出目录下所有的.txt文件
each_file = os.path.join(os.getcwd(),each_file)
temp.append(each_file)
if os.path.isdir(each_file):
search_file(each_file)
os.chdir(os.pardir)
def pos_in_line(each_row,target): #查找每一行
column = []
begin = each_row.find(target)
while begin != -1:
column.append(begin + 1)
begin = each_row.find(target, begin + 1)
return column
def row_column(target): #确定行号和列号
for each_file_1 in temp: #调用在列表temp下保持的每个txt文件
f = open(each_file_1)
count = 0
pos = {}
txt = []
lines = f.readlines()
for each_row in lines: #每个txt文件的每一行
count += 1
if target in each_row:
pos[count] = pos_in_line(each_row,target) #把列号保存在字典pos里
txt.append(each_file_1)
news_txt = []
for direction in txt: #列表去重
if direction not in news_txt:
news_txt.append(direction)
for i in news_txt: #打印
print('========')
print('在文件'+ i + '中找到关键字' + target)
for count1 in pos.keys(): #输出每一个包含target字符串的行和列
print('关键字出现在第:%s行,第%s个位置' %(count1,str(pos[count1])))
f.close()
temp = []
lines = []
target = input('请输入要查找的字符串:')
check = input('是否打印关键字具体位置yes/no:')
if check == 'yes':
search_file(os.getcwd())
row_column(target)
|