辞書をtxtファイルに書き込んで、それを読み戻しますか? [重複] 質問する

辞書をtxtファイルに書き込んで、それを読み戻しますか? [重複] 質問する

辞書を txt ファイルに書き込もうとしています。次に、 でキーを入力して辞書の値を読み取りますraw_input。 1 つの手順が足りないような気がしますが、しばらく探していました。

このエラーが発生します

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)

ベストアンサー1

やってみましたjsonモジュール? 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}

おすすめ記事