本帖最后由 叼辣条闯世界 于 2021-7-31 12:30 编辑 global file_hz,position
def search_keywords(file_path,key_words):
row_count = 0
"""search for key words in certain file, pointing\
out the number of line and position"""
import os
os.chdir(file_path)
all_file=os.listdir()
pickup_file = []
for each in all_file:
if os.path.isfile(each):
file_hz = os.path.splitext(each)
if file_hz[1] == '.txt':
try:
f = open(each,encoding='gb18030')
file_read = f.read()
except:
f = open(each,encoding='utf8')
file_read = f.read()
row_count = 0
if key_words in file_read:
position = dict()
pickup_file.append(os.path.join(os.getcwd(),each))
print('在文件' + each + '中找到关键字:%s'%key_words)
f.seek(0,0)
file_get_lines = int(len(f.readlines()))
f.seek(0,0)
for i in range(file_get_lines):
file_readlines = f.readline()
if key_words in file_readlines:
row_count += 1
key_pos = file_readlines.find(key_words)+1
#while key_pos != -1:
key_pos = file_readlines.find(key_words)+1
print('关键字出现在第%s行,第%s个位置'%(row_count,key_pos))
#break
else:
row_count += 1
else:
search_keywords(each, key_words)
os.chdir(os.pardir)
file_path = input('请输入要查找的文件路径:')
key_words = input('请输入要查找的关键字:')
search_keywords(file_path,key_words)
input('任意键退出')
|