我正在尝试将字典写到txt文件中。然后使用raw_input
键来读取dict值。我觉得我只是错过了一步,但我已经寻找了一段时间。
我得到了这个错误
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)
发布于 2012-06-14 13:14:28
你试过the json module吗?JSON格式非常类似于python字典。而且它是人类可读/可写的:
>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))
此代码转储为文本文件
$ cat text.txt
{"two": 2, "one": 1}
您也可以从JSON文件加载:
>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}
发布于 2013-09-15 16:27:47
我创建了我自己的函数,它们工作得非常好:
def writeDict(dict, filename, sep):
with open(filename, "a") as f:
for i in dict.keys():
f.write(i + " " + sep.join([str(x) for x in dict[i]]) + "\n")
它将首先存储键名,然后存储所有值。请注意,在本例中,我的dict包含整数,所以这就是它转换为int
的原因。这很可能是您需要针对您的情况进行更改的部分。
def readDict(filename, sep):
with open(filename, "r") as f:
dict = {}
for line in f:
values = line.split(sep)
dict[values[0]] = {int(x) for x in values[1:len(values)]}
return(dict)
发布于 2015-12-09 09:50:52
您可以遍历键-值对并将其写入文件
pair = {'name': name,'location': location}
with open('F:\\twitter.json', 'a') as f:
f.writelines('{}:{}'.format(k,v) for k, v in pair.items())
f.write('\n')
https://stackoverflow.com/questions/11026959
复制相似问题