python - 将 dict 写入 txt 文件并将其读回?

标签 python

我正在尝试将字典写入 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)

最佳答案

你试过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}

关于python - 将 dict 写入 txt 文件并将其读回?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11026959/

相关文章:

Python:从列表创建字典并自动生成/增加键(列表是实际键值)?

python - 使用 pandas.SparseSeries.from_coo() 函数的非 NDFFrame 对象错误

python - 获取从一个时间到另一个时间的数据

python - 从 JSON Discord PY 中删除所有用户信息

python - 为什么 urllib.request.urlopen 有时不起作用,但浏览器可以?

python - spaCy 句子分割在引号上失败

python - 按百分比随机划分并存储 SQL 表

python - 如何使用 3 个列表在 Python 中创建嵌套字典

python - 使用 ASN.1 解码,其中 substrate 包含一些不透明数据

python - 安装python包以纠正anaconda环境