将字典列表作为字符串写入时遇到问题

时间:2012-01-08 20:08:08

标签: python dictionary

我正在尝试编写一个程序,用于创建一个包含联系人姓名,电子邮件,电话号码等的地址簿。我将每个联系人存储为字典,然后将每个人(字典)放入全局列表中。然后,我使用repr()将列表转换为字符串,并将其写入文件。当我尝试重新加载列表并写下它包含的内容时,我得到一个空字典列表。请帮我弄清楚出了什么问题。

这是我的代码:

list = []
listfile = 'phonebook.txt'

class bookEntry(dict):
    total = 0

    def __init__(self):
        bookEntry.total += 1
        self.d = {}

    def __del__(self):
        bookEntry.total -= 1

class Person(bookEntry):
    def __init__(self, n):
        bookEntry.__init__(self)
        self.n = n
        print '%s has been created' % (self.n)

    def addnewperson(self, n, e = '', ph = '', note = ''):
        f = file(listfile, 'w')

        self.d['name'] = n
        self.d['email'] = e
        self.d['phone'] = ph
        self.d['note'] = note

        list.append(self)
        listStr = repr(list)
        f.write(listStr)

        f.close()

我使用startup()函数启动程序:

def startup():
    aor = raw_input('Hello! Would you like to add an entry or retrieve one?')
    if aor == 'add':
        info = raw_input('Would you like to add a person or a company?')
        if info == 'person':
            n = raw_input('Please enter this persons name:')
            e = raw_input('Please enter this persons email address:')
            ph = raw_input('Please enter this persons phone number:')
            note = raw_input('Please add any notes if applicable:')

            X = Person(n)
            X.addnewperson(n, e, ph, note)
startup()

我将这些答案添加到提示中:

'''
    Hello! Would you like to add an entry or retrieve one?add
    Would you like to add a person or a company?person
    Please enter this persons name:Pig
    Please enter this persons email address:pig@brickhouse.com
    Please enter this persons phone number:333-333-3333
    Please add any notes if applicable:one of three
    Pig has been created
'''

当我打开phonebook.txt时,这就是我所看到的:

[{}]

为什么要返回空字典?

3 个答案:

答案 0 :(得分:1)

您应该保存self.d而不是self

  alist.append(self.d)
  listStr = repr(alist)
  f.write(listStr)

btw不要使用 list 作为变量的名称,而是覆盖关键字list

答案 1 :(得分:1)

您派生自dict,但将所有元素存储在成员d中。因此,repr会为您提供一个表示空dict的字符串。如果您想将bookEntry用作dict,请使用

插入信息
self['name'] = n

而不是

self.d['name'] = n

(但实际上,你不应该继承dict。此外,请不要使用list作为标识符,它是内置的名称。)

答案 2 :(得分:0)

您的问题是X.d字典与“bookEntry”继承的字典不同。因此,repr(X)没有显示X.d

解决方案可能是覆盖BookEntry中的repr:

e.g。

def __repr___(self):
  return repr(self.d)
相关问题