0

I'm trying to write a function that allows a user to update a contact's address book. I want to be able to update the first and last name as well as the mobile and home number. This is what I have so far:

def update_contact():
    phonebook = open("contacts.txt", "r")
    readfile = phonebook.read()
    print(readfile)
    contact = input("Which contact do you want to update: ")
    if contact in readfile:
        last = input("Enter new last name: ")
        phonebook = open("contacts.txt", "a")
        for line in open("contacts.txt"):
            line = line.replace(contact, last)
            phonebook.write(line)

user1558604
  • 947
  • 6
  • 20
  • This is really broad. Can you refine what you actually need help with? – user1558604 Dec 06 '19 at 18:14
  • I created a phonebook whose contacts are saved on a text file. What I'm trying to do is to be able to update a contact's information through the use of a user's input. – Valar_Morghulis Dec 06 '19 at 18:17
  • Are you getting an error in the code above or unexpected results? What is you input, the expected output, and the output you are receiving? – user1558604 Dec 06 '19 at 18:19
  • When I enter the new last name it creates a copy of the contact with the change instead of updating the contact. – Valar_Morghulis Dec 06 '19 at 18:21
  • Does this answer your question? [Is it possible to modify lines in a file in-place?](https://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place) – QuantumLicht Dec 06 '19 at 18:23
  • You should look at this https://stackoverflow.com/questions/5453267/is-it-possible-to-modify-lines-in-a-file-in-place. If I understood correctly, you are trying to do modify the file in-place. – QuantumLicht Dec 06 '19 at 18:24

0 Answers0