0

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!

Op_Rags
  • 23
  • 1
  • 7
  • it'd be much easier if you kept the name, address and phone all on the same line separated by a pipe char or something – wpercy Jul 26 '18 at 17:51
  • @wpercy would that look something like this: `f.write(name_new + '|' + address + '|'...)` – Op_Rags Jul 26 '18 at 17:53
  • yep, maybe wrap the pipe in a couple of spaces `(... + ' | ' + ...)` – wpercy Jul 26 '18 at 17:57
  • @wpercy okay thank you that does look a lot nicer, how would I now then print out that line of the file to the console? – Op_Rags Jul 26 '18 at 17:58
  • @wpercy I was able to work that question out, detailed above. thanks for your help! – Op_Rags Jul 26 '18 at 18:14
  • Yep, that's exactly how I would have done it. You can actually answer your own question - it'll be more helpful for anyone that comes here looking for a similar solution. – wpercy Jul 26 '18 at 18:27

1 Answers1

0

Thanks 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 in the comments, helping with the organization, making the line to a single line instead of multiple lines! Thank you so much!

Op_Rags
  • 23
  • 1
  • 7