首页 > 解决方案 > 有人可以告诉我如何将 .text 文件放入包含数字和字符串的字典中

问题描述

我正在制作一个关于联系人保护程序的项目,但我无法读取代码中的单个联系人......请帮助我......我正在提供代码和问题如果你可以向我提供整个部分查找单个用户或所有相关用户...谢谢...

what = input("Do you want to read a single contact(y, n): ")
if what == 'y':
    who = input("Please Enter the name: ")
    a = open('contacts.txt', 'a')
    for line in a:
        k, v = line.strip().split('=')
        users[k.strip()] = v.strip()
        a.close()

    for i in users:
        if who.lower() == i.lower() or i.startswith(who[:3]):
            print(i)

这是错误:'

Traceback(最近一次通话最后一次):文件“C:/Users/Teerth Jain/Desktop/teerth_made_projects/contacts.py”,第 18 行,在 for line in a:io.UnsupportedOperation:不可读在此处输入代码

'

标签: pythonpython-3.xdictionarytext-files

解决方案


您以写入模式而不是读取模式打开文件,使用"r"代替"a"(附加到文件)

a = open('contacts.txt', 'r')

另外,不确定您是否正确包含了问题的缩进,但a.close()应该在 for 循环之外

如评论中所述,使用with优于显式关闭文件。

with open('contacts.txt', "r") as a:
    for line in a:
        k, v = line.strip().split('=')
        users[k.strip()] = v.strip()

推荐阅读