|
马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
import os
def search_files(key,detail):
all_txt_files=[]
for each_file in os.listdir(os.curdir):
if os.path.splitext(each_file)[1]=='.txt':
all_txt_files.append(each_file)
for each_txt_file in all_txt_files:
search_in_file(each_txt_file,key)#调取一个可以找出文件中关键字的函数
if detail in ['yes','Yes','YES']:
print('该文件所在位置%s有关键字'%(each_txt_file,key))
for each in line_dict.keys():
ptint('在该文件中第%s行%s位置'%(each,line_dict[each]))#如果detail是yes 调用一个打印函数
if os.path.isdir(each_file):
search_files(key,detail)
os.chdir(os.pardir)
def search_in_file(each_file,key):
f1=open(each_file)
f=f1.read()
line_dict=dict()
count=0
for each_line in f:
count+=1
if key in each_line:
line_dict[count]=each_line.count(key)
f1.close()
return line_dict
key=input('请将该代码放在待查找的文件夹中,请输入关键字:')
detail=input('请问是否需要打印关键字%s在文件中的具体位置(yes/no)'%key)
search_files(key,detail)
请将该代码放在待查找的文件夹中,请输入关键字:愿
请问是否需要打印关键字愿在文件中的具体位置(yes/no)yes
Traceback (most recent call last):
File "C:/Users/lenovo/Desktop/查找关键字.py", line 35, in <module>
search_files(key,detail)
File "C:/Users/lenovo/Desktop/查找关键字.py", line 10, in search_files
print('该文件所在位置%s有关键字'%(each_txt_file,key))
TypeError: not all arguments converted during string formatting
>>>
你这代码问题太多。
1就像楼上说的
print('该文件所在位置%s有关键字'%(each_txt_file,key)) 这本该只有1个参数
第2 递归遍历目录查找文件
def search_files(key,path=''):
if path!='':
os.chdir(path)
for each_file in os.listdir(os.curdir):
if os.path.splitext(each_file)[1]=='.txt':
all_txt_files.append(each_file)
for each_txt_file in all_txt_files:
search_in_file(each_txt_file,key)#调取一个可以找出文件中关键字的函数
if detail in ['yes','Yes','YES']:
print('该文件所在位置%s有关键字'%(each_txt_file,key))
for each in line_dict.keys():
ptint('在该文件中第%s行%s位置'%(each,line_dict[each]))#如果detail是yes 调用一个打印函数
if os.path.isdir(each_file):
search_files(key,each_file)
os.chdir(os.pardir)
第3 文件编码问题
提供给你参考,具体自己捉摸。
|
|