写一个字典到txt文件并读回去?
我正在尝试将字典写到txt文件。然后使用键入键,以读取dict值raw_input
。我感觉好像只想走一步,但现在已经找了一段时间。
我得到这个错误
File "name.py", line 24, in reading
print whip[name]
TypeError: string indices must be integers, not str
我的代码:
#!/usr/bin/env python
from sys import exit
class Person(object):
def __init__(self):
self.name = ""
self.address = ""
self.phone = ""
self.age = ""
self.whip = {}
def writing(self):
self.whip[p.name] = p.age, p.address, p.phone
target = open('deed.txt', 'a')
target.write(str(self.whip))
print self.whip
def reading(self):
self.whip = open('deed.txt', 'r').read()
name = raw_input("> ")
if name in self.whip:
print self.whip[name]
p = Person()
while True:
print "Type:\n\t*read to read data base\n\t*write to write to data base\n\t*exit to exit"
action = raw_input("\n> ")
if "write" in action:
p.name = raw_input("Name?\n> ")
p.phone = raw_input("Phone Number?\n> ")
p.age = raw_input("Age?\n> ")
p.address = raw_input("Address?\n>")
p.writing()
elif "read" in action:
p.reading()
elif "exit" in action:
exit(0)
-
您的代码 几乎正确 !没错,您只差一步。当您读入文件时,您将以字符串形式读取它;但是您想将字符串转换成字典。
您看到的错误消息是因为
self.whip
是字符串,而不是字典。我首先写道,您可以只将字符串输入其中,
dict()
但这不起作用!您需要做其他事情。例
这是最简单的方法:将字符串输入
eval()
。像这样:def reading(self): s = open('deed.txt', 'r').read() self.whip = eval(s)
您可以一行完成它,但是我认为这种方式看起来很混乱:
def reading(self): self.whip = eval(open('deed.txt', 'r').read())
但是
eval()
有时不推荐。问题是,eval()
它将评估 任何
字符串,如果有人诱骗您运行真正棘手的字符串,则可能会发生不良情况。在这种情况下,您只是eval()
在自己的文件上运行,所以应该可以。但是因为
eval()
有用,所以有人选择了一种更安全的替代方法。这称为literal_eval
,您可以从名为的Python模块中获取该代码ast
。import ast def reading(self): s = open('deed.txt', 'r').read() self.whip = ast.literal_eval(s)
ast.literal_eval()
只会评估转换成基本Python类型的字符串,因此,棘手的字符串无法对您的计算机造成不良影响。编辑
实际上,Python中的最佳实践是使用
with
语句来确保正确关闭文件。重写以上内容以使用以下with
语句:import ast def reading(self): with open('deed.txt', 'r') as f: s = f.read() self.whip = ast.literal_eval(s)
在最流行的Python(称为“
CPython”)中,您通常不需要该with
语句,因为内置的“垃圾收集”功能将确定您已完成文件并会为您关闭文件。但是其他Python实现,例如“
Jython”(用于Java VM的Python)或“
PyPy”(具有即时代码优化的非常酷的实验系统)可能无法为您关闭文件。养成使用的习惯是很好的with
,而且我认为这使代码很容易理解。