I am looking for a way to print a set of text in a file. I am currently working with the scenario in which a user 'looks up' a name, and if that name is found in the file, it will print the name, address, and phone number.
I need to know when the name is found, how to print the following lines containing the address and phone number.
This is the code I have currently:
def look_up(name):
# checking if contact is already added
if name in open('contacts.txt').read():
print name
# print the address
# print the phone number
else:
# if contact not found, asks to add to book.
q = raw_input('Name not found, add to contact book?')
if q == 'yes':
# adding the info to the 'contacts.txt' file
name_new = raw_input('Enter the full name: ')
address = raw_input('Enter the address: ')
phone = raw_input('Enter the phone number: ')
f = open('contacts.txt', 'w')
f.write(name_new + '\n')
f.write(address + '\n')
f.write(phone + '\n')
f.close()
EDIT
Thank to this post, and the help of @wpercy, I was able to find the best answer.
This bit of code:
f = open('contacts.txt', 'r')
lines = f.readlines()
for line in lines:
if name in line:
print (line)
f.close()
allows for printing of a given line that contains the user passed 'name'.
The contribution of @wpercy can be seen below, helping with the organization, making the line to a single line instead of multiple lines! Thank you so much!