python - 有人可以告诉我如何将 .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:不可读在此处输入代码
'
解决方案
您以写入模式而不是读取模式打开文件,使用"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()
推荐阅读
- python - 如何使用固定到 Thud 的 Yocto 升级 Python?
- angular - 带有多个选项的角度材料选择下拉菜单不隐藏在对话框中
- python - 用文本内容谷歌驱动器api创建一个新文件?
- python - 如何打印具有重复字符的字符串?
- pandas - 迭代数据框列的多个操作(应用函数?)
- java - 如何检查 int 是否包含特定数字?
- node.js - 如何获取代表任何一组 API 方法的 Typescript 类型?
- javascript - TypeScript 类继承的行为与其等效的 ES6 不同
- python - 试图找出 NameError:在 Python 程序中
- c# - 在设计期间在 VS(10) 中调试 C# .NET 自定义组件/控件