import os
def search(path, key,decide):
os.chdir(path)
list1 = os.listdir(os.curdir)
for each_file in list1:
if os.path.isdir(each_file):
search(each_file, key,decide)
os.chdir(os.pardir)
i = os.path.splitext(each_file)
if i[1] == '.txt':
with open(each_file) as f:
f_path = os.getcwd() + os.sep + each_file
row = 0
if key in f.read(): #<---read()后文件指针指向文件尾
print('===================================================')
print('在文件【%s】中找到关键字【%s】' % (f_path, key))
if decide.upper() == 'YES':
pos = dict() #pos用来存放key的位置信息
f.seek(0) #<--加一句,把文件指针复位到开始
for each_line in f: #<---如果不调整文件指针,指针在尾部,这段循环不会被执行,后面也不会被打印
row += 1
column_list = [] #用来存放每行含key的所有列
column = each_line.find(key) + 1
if column == 0:
continue
while column != 0:
column_list.append(column)
column = each_line.find(key,column) + 1
pos[row] = column_list
print('关键字出现在第 %d 行,第 %s 个位置。' % (row,str(column_list)))
path = os.getcwd()
key = input('请将该脚本放于待查找的文件夹内,请输入关键字:')
decide = input('请问是否需要打印关键字【%s】在文件中的具体位置(YES/NO):' % key)
search(path, key,decide)
|