如何从该文本文件中读取字典?

时间:2018-09-12 19:51:34

标签: python python-3.x

我还是python的新手,我正在玩将数据保存到文本文件的操作。我的问题是,当我尝试访问字典时,它出现此错误TypeError: string indices must be integers,但我不知道如何转换它们。

这是我文件中的内容:

Student 1/:{ "Topic 1" : 0,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 4}
Student 2/:{ "Topic 1" : 1,"Topic 2" : 2,"Topic 3" : 0,"Topic 4" : 0}
Student 3/:{ "Topic 1" : 1,"Topic 2" : 0,"Topic 3" : 0,"Topic 4" : 1}

这是我的代码:

import ast #I thought this would fix the problem

def main():
  data = {}
  with open("test.txt") as f:
    for line in f:
        content = line.rstrip('\n').split('/:')
        data[content[0]] = ast.literal_eval(content[1])
  f.close()
  print(data["Student 1"["Topic 1"]]) # works if I only do data[Student 1]

main()

是否有一种更有效的数据存储方式?

2 个答案:

答案 0 :(得分:1)

我建议使用JSON将数据写到文本文件中 https://docs.python.org/3/library/json.html

您可以使用json.dumps方法创建可写入文件的JSON数据,并使用json.loads方法将文件中的文本转换回字典中

答案 1 :(得分:1)

好吧,既然您的问题要求“一种更有效的数据存储方式”,我会说“是”!

https://docs.python.org/3/library/shelve.html

Shelve是一个很好的工具,可以永久存储字典并随时更改/编辑字典。我目前正在将它用于我正在进行的一个不一致的机器人项目,到目前为止,一切都很棒。

以下是一些使用入门技巧(直接从我链接的页面中提取)。

import shelve

d = shelve.open(filename)  # open -- file may get suffix added by low-level
                           # library

d[key] = data              # store data at key (overwrites old data if
                           # using an existing key)
data = d[key]              # retrieve a COPY of data at key (raise KeyError
                           # if no such key)
del d[key]                 # delete data stored at key (raises KeyError
                           # if no such key)

flag = key in d            # true if the key exists
klist = list(d.keys())     # a list of all existing keys (slow!)

# as d was opened WITHOUT writeback=True, beware:
d['xx'] = [0, 1, 2]        # this works as expected, but...
d['xx'].append(3)          # *this doesn't!* -- d['xx'] is STILL [0, 1, 2]!

# having opened d without writeback=True, you need to code carefully:
temp = d['xx']             # extracts the copy
temp.append(5)             # mutates the copy
d['xx'] = temp             # stores the copy right back, to persist it

# or, d=shelve.open(filename,writeback=True) would let you just code
# d['xx'].append(5) and have it work as expected, BUT it would also
# consume more memory and make the d.close() operation slower.

d.close()                  # close it
相关问题