我想做一個python聯繫人管理器,並且我做了一個搜索contacts.txt
文件的函數。它可以成功地找到'你',或者列表上的第一個聯繫人,但它找不到其他人。我不知道爲什麼或如何發生這種情況。Python在第一行以外的任何行上找不到短語?
功能
def readFile(self):
f = open('contacts.txt', 'r')
lines = f.readlines()
cmd = str(input("Type in a contact REFERENCE name.\n"))
lookup = cmd
with open('contacts.txt') as myFile:
for num, line in enumerate(myFile, 1):
if lookup.upper() in line:
print(lines[num - 1])
print(lines[num])
print(lines[num + 1])
print(lines[num + 2])
print(lines[num + 3])
self.managerMenu()
else:
print("Contact not found.")
self.managerMenu()
contacts.txt
Contact: YOU
First Name: FELIX
Last Name: MARTIN
Number: (555)-555-5555
Address: 123 SESAME STREET
Contact: DAD
First Name: JOHN
Last Name: SMITH
Number: (555)-555-5555
Address: 123 SESAME STREET
當我運行該文件,打字readfile
然後you
產生這樣的:
Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
readfile
Type in a contact REFERENCE name.
you
Contact: YOU
First Name: FELIX
Last Name: MARTIN
Number: (555)-555-5555
Address: 123 Sesame Street
但是,當我做同樣的事情與DAD
聯繫:
Available Commands: Info, ReadFile, DeleteContact, EditContact, AddContact, quit()
readfile
Type in a contact REFERENCE name.
dad
Contact not found.
我在c9.io上運行Python 3.4。任何幫助將不勝感激。
什麼是'self.managerMenu()'? –
你爲什麼要讀這個文件兩次?你可以閱讀所有的行,並且一次使用這個列表或者一個列表,就像你以後做的那樣(更好) – Pynchia
註釋掉'self.managerMenu()' - 我敢打賭它干擾你的循環 – Gerrat