Python通讯录运行报TypeError: 'str' object is not callable错误求助
问题根因
- 第一处错误:
contacts = file.read()从文件读取得到的是字符串类型,并非预期的字典结构,无法直接调用字典的update()、键索引等方法 - 第二处错误:遍历字典时错误添加括号写作
contacts(),括号代表执行调用操作,但contacts是字符串不是可调用对象,直接触发你收到的TypeError: 'str' object is not callable报错 - 第三处错误:当前代码修改通讯录数据后没有回写到
directory.txt,修改内容仅保存在内存中,程序退出后所有变更都会丢失 - 补充说明:Python要求函数必须在调用前定义,你当前代码的函数定义顺序符合要求,问题和函数定义顺序无关
修复后完整代码
import ast # 读取通讯录文件,转换为字典格式 try: with open("directory.txt", "r", encoding="utf-8") as f: file_content = f.read().strip() # 文件为空时初始化为空字典 contacts = ast.literal_eval(file_content) if file_content else {} except FileNotFoundError: # 文件不存在时初始化空字典 contacts = {} def new(): print("Please enter the name of the new contact.") name = input() print("Please enter the number of the new contact.") num = input() contacts.update({name: num}) print("Contact has successfully been added.") def view(): # 遍历字典使用items()方法,不要加括号 for keys, values in contacts.items(): print("\n*************************************************") print("Name:", keys) print("Number:", values) print("*************************************************\n") def edit(): # 遍历字典使用items()方法,不要加括号 for keys, values in contacts.items(): print("\n*************************************************") print("Name:", keys) print("Number:", values) print("*************************************************\n") print("Type the name of the contact you would like to edit.") global name_two name_two = input() print("If you would like to edit the number, type 'number'.\nIf you would like to edit the name, type 'name'.\nIf you would like to delete this contact, type 'delete'.") edit_choice = input().lower() if edit_choice == "number": num_edit() elif edit_choice == "name": name_edit() elif edit_choice == "delete": delete() def num_edit(): print("What would you like to change the number to?") num_two = input() contacts[name_two] = num_two print("Contact successfully changed.") def name_edit(): num_save = contacts[name_two] del contacts[name_two] print("Enter the new name for the contact.") name_new = input() contacts.update({name_new: num_save}) print("Contact successfully changed.") def delete(): del contacts[name_two] print("Contact successfully deleted.") print("Welcome to the Contacts Book.") print("*****************************\n") print("If you would like to make a new contact, type 'new'.\nIf you would like to view your contacts, type 'view'.\n If you would like to edit your contacts, type 'edit'.\nIf you would like to exit, type 'exit'") mode = input().lower() if mode == "new": new() elif mode == "view": view() elif mode == "edit": edit() else: print("Goodbye.") # 所有操作完成后将变更回写到文件 with open("directory.txt", "w", encoding="utf-8") as f: f.write(str(contacts))
补充说明
修改时额外把edit变量名改名为edit_choice,避免和edit()函数重名导致后续调用出错。使用ast.literal_eval转换字符串为字典,比直接用eval更安全,不会执行恶意代码。
内容的提问来源于stack exchange,提问作者Nomzz
相关产品推荐
相关产品推荐

