我正在嘗試將字典寫(xiě)到txt文件。然后使用鍵入鍵,以讀取dict值raw_input。我覺(jué)得我只差一步,但我一直在尋找一段時(shí)間。我得到這個(gè)錯(cuò)誤File "name.py", line 24, in reading print whip[name]TypeError: string indices must be integers, not str我的代碼:#!/usr/bin/env pythonfrom sys import exitclass 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)
3 回答

慕哥6287543
TA貢獻(xiàn)1831條經(jīng)驗(yàn) 獲得超10個(gè)贊
您是否嘗試過(guò)json模塊?JSON格式與python字典非常相似。它是人類(lèi)可讀/可寫(xiě)的:
>>> import json
>>> d = {"one":1, "two":2}
>>> json.dump(d, open("text.txt",'w'))
此代碼轉(zhuǎn)儲(chǔ)到文本文件
$ cat text.txt
{"two": 2, "one": 1}
您也可以從JSON文件加載:
>>> d2 = json.load(open("text.txt"))
>>> print d2
{u'two': 2, u'one': 1}
添加回答
舉報(bào)
0/150
提交
取消