BANL16fd1c9a1:file_exceptions jjimmy$ python3 search_cofee_records.py
Please enter an item name:-Tea
Description will be :- Tea
QUANTITY will be :- 500
BANL16fd1c9a1:file_exceptions jjimmy$
BANL16fd1c9a1:file_exceptions jjimmy$ cat search_cofee_records_for.py
def main():
infile=open('coffee.txt','r')
search=input("Please enter an item :-")
for line in infile:
line=line.rstrip('\n')
if (line==search):
print("Description:-",line)
infile.close()
main()
答案 0 :(得分:0)
只需使用布尔标志:
stop = False
def main():
infile = open('coffee.txt','r')
search = input("Please enter an item :-")
for line in infile:
line=line.rstrip('\n')
if stop:
print(line)
break ## or stop = False if you want to keep on checking for more matches
if (line==search):
print("Description:-",line)
stop = True
infile.close()
基本上,我告诉python,找到匹配项后,我想在下一行停止,这就是为什么我使用stop
标志,然后我break
退出循环,以防止随后print
行每一行。
答案 1 :(得分:0)
我认为
line=line.rstrip('\n')
应该在循环之前,并且应该将范围用于循环
def main():
infile=open('coffee.txt','r')
search=input("Please enter an item :-")
lines=line.rstrip('\n')
for i in range(len(lines)):
if (lines[i]==search):
print("Description:-",line)
print(line[i+1])
infile.close()
main()
答案 2 :(得分:0)
这应该很好,除非您有一个不想加载到内存中的千兆字节文件(大多数作业没有这样的文件=)
def main():
search=input("Please enter an item :-")
with open('coffee.txt') as infile :
data = [i.strip() for i in infile.readlines()]
for a,b in zip(data,data[1:] :
if a == search :
print("Description:-", a)
print("QUANTITY will be :-", b) # the next line
main()