In: Computer Science
This task is solved in Python 3.
Develop a program that can change the phone number of a person in phone.txt (hint: the easiest thing is probably to make a new version of the file, and then delete the old one before the new is renamed to phone.txt)
Name: John
Old phone number: 99776612
New number: 99889999
>>>
phone.txt |
Replaced by ------> |
phone.txt |
Mary 98654321 June 99776655 Chris 99112233 Viv 98554455 John 99776612 Joe 97888776 Rick 99455443 Susan 98122134 Jill 99655732 Bob 98787896 |
Mary 98654321 June 99776655 Chris 99112233 Viv 98554455 John 99889999 Joe 97888776 Rick 99455443 Susan 98122134 Jill 99655732 Bob 98787896 |
# Python Code
# read phone.txt
try:
file = open("phone.txt", 'r')
phone_book = []
for i in file:
line = i.rstrip().split(" ")
phone_book.append(line)
# close the file
file.close()
# delete file
del(file)
name = input("Name: ")
old_phone_number =input("Old phone number: ")
new_number = input("New Number: ")
# open file writing mode
file1 = open("phone.txt", 'w')
# search number in the list
for i in phone_book:
if i[1] == old_phone_number:
i[1] = new_number
# now write the complete data to phone.txt
file1.write(i[0]+" "+i[1]+"\n")
# close the file
file1.close()
except FileNotFoundError:
print("File not found")
# file
# Output
//If you need any help regarding this solution... please leave a comment. thanks