python basic phonebook application with IO

Viewed 91

I had a basic phone book application that adds, lookup, updates, and deletes a record and it works fine. I wanted to add functionality to it in which when I close and restart the program the previously added records are still there saved in a file. And when I want to add more records to the dictionary file it will also be appended to the file but I am running into 2 issues the first one is when I try to integrate my saved file with my dictionary I get error dictionary update sequence element #0 has length 1; 2 is required so I for some reason can't read the file to check if I have a record in the file with the same name for example. The second issue is when I Quit the program I added a save Record function which when run adds the newly added records onto the file to save it before it quits but when I print it, it only shows the first string printed the other is not shown I don't know what is causing this. Any help is appreciated thanks in advance.

#!/usr/bin/python3
import os.path
from os import path


    
phones = {}
if path.exists('phones.txt'):
    with open("phones.txt") as f:
        phones = dict(x.rstrip().split(None, 1) for x in f)
else: 
    phoneFile = open("phones.txt", "w")
    print("File Created")
    phoneFile.close()
    with open("phones.txt") as f:
        phones = dict(x.rstrip().split(None, 1) for x in f)
       
def menu():
    print("1. Add a record")
    print("2. Lookup a record")
    print("3. Update a record")
    print("4. Remove a record")
    print("5. List all records")
    print("6. Quit")
    selection = input("Please make your selection from the options above: ")
    if(selection == '1'):
        addRecord()
        menu()
    elif(selection == '2'):
        lookupRecord()
        menu()
    elif(selection == '3'):
        updateRecord()
        menu()
    elif(selection == '4'):
        removeRecord()
        menu()
    elif(selection == '5'):
        listRecords()
        menu()
    elif(selection == '6'):
        saveRecords()
        print("Goodbye")
        #exit(0)
    else:
        print("Sorry, invalid input, try again.")
        menu()

def addRecord():
    a = str(input("Person's name to add to record: "))
    b = int(input("Number to add to record: "))
    if a in phones:
        print("Name already in records, Please choose another name")
    else:
        phones[a] = b
        print(phones)

def lookupRecord():
    a = str(input("Person's name to look: "))
    if a in phones:
        print(a + "'s number is " + str(phones.get(a)))
    else:
        print("Person not found")

def updateRecord():
    a = str(input("Person's name to update: "))
    if a in phones:
        b = int(input("New phone number to update: "))
        phones[a] = b
        print(phones)
    else:
        print(a + " is not in your phone book")

def removeRecord():
    a = str(input("Person's name to remove: "))
    if a in phones:
        del phones[a]
        print(a + " removed from phone book")
    else:
        print("Name not found")

def listRecords():
    for i in phones.items():
        print(i)
        
def saveRecords():
    for i in phones.items():
        writePhoneFile = open("phones.txt", "w")
        finalRecord = ':'.join('%s' %id for id in i)
        writePhoneFile.write(finalRecord)
        readPhoneFile = open("phones.txt", "r+")
        print(readPhoneFile.read())
    

def main():
    print("== Welcome to the Phonebook App ==")
    menu()

if __name__ == "__main__":
    main()

1 Answers

use below because phone number in integer :

phones = dict( (x.rstrip().split(':')[0] , int(x.rstrip().split(':')[1]))  for x in f)

in addition, open the file outside for loop in saverecords:

writePhoneFile = open("phones.txt", "w")
    for i in phones.items():
        print(i)
        finalRecord = ':'.join('%s' %id for id in i)+'\n'
        writePhoneFile.write(finalRecord)
    writePhoneFile.close() 
Related