请求帮助,看了两个小时了这点代码改不对import os
import os.path as op
def find_name(name):
all_file = os.listdir(os.curdir)
for each_file in all_file:
if op.splitext(each_file)[1] == '.txt':
f1 = open(each_file,'r')
count = 0
if name in each_file:
print('在文件【%s】中找到关键字【%s】'%(each_file,name))
for each_line in f1:
count += 1
if name in each_line:
print('关键字出现在%d行,第%s个位置'%(count,find_name(name,each_line)))
f1.close()
if op.isdir(each_file):
find_name(each_file)
os.chdir(os.pardir)
def find_num(name, string):
where = []
index = string.find(name)
while index != -1:
where.append(index + 1)
index = string.find(name, index+1)
return where
name1 = input('请将该脚本防御带查找的文件夹内,请输入关键字:')
choice = input('请问是否要打印关键字【%s】在文件夹中的具体位置(YES/NO):'%(name1))
if choice == 'YES'or choice == 'yes':
find_name(name1)
一直报我递归的错。。。。18 行和 32 行
本帖最后由 Twilight6 于 2020-7-16 20:17 编辑
代码很多错误,帮你改了,你自己对照着看看吧:
import os
import os.path as op
def find_name(name):
all_file = os.listdir(os.curdir)
for each_file in all_file:
if op.splitext(each_file)[1] == '.txt':
f1 = open(each_file)
count = 0
temp = []
file_path = True
for each_line in f1:
count += 1
if name in each_line:
temp = find_num(name,each_line)
if temp != []:
if file_path:
print('|----文件 %s' % os.getcwd() + op.sep + each_file)
file_path = False
print('|-关键字出现在%d行,第%s个位置' % (count,temp))
f1.close()
if op.isdir(each_file):
os.chdir(each_file)
find_name(name)
os.chdir(os.pardir)
def find_num(name, string):
where = []
index = string.find(name)
while index != -1:
where.append(index + 1)
index = string.find(name, index+1)
return where
name1 = input('请将该脚本防御带查找的文件夹内,请输入关键字:')
choice = input('请问是否要打印关键字【%s】在文件夹中的具体位置(YES/NO):'%(name1))
if choice == 'YES'or choice == 'yes':
find_name(name1)
|