简体   繁体   English

python 基本电话簿应用程序与 IO

[英]python basic phonebook application with IO

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当我想向字典文件添加更多记录时,它也会被附加到文件中,但我遇到了 2 个问题,第一个问题是当我尝试将保存的文件与字典集成时,我收到错误dictionary update sequence element #0 has length 1; 2 is required 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. dictionary update sequence element #0 has length 1; 2 is required ,因此我由于某种原因无法读取文件以检查文件中是否有同名记录。 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.第二个问题是当我退出程序时我添加了一个保存记录 function 运行时将新添加的记录添加到文件中以在退出之前保存它但是当我打印它时,它只显示打印的第一个字符串,另一个没有显示我不知道这是什么原因造成的。 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()

use below because phone number in integer:使用下面的电话号码,因为 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:另外,在saverecords中打开for循环外的文件:

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() 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM