簡體   English   中英

如何從該文本文件中讀取字典?

[英]How to read a dictionary from this text file?

我對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()

是否有更有效的數據存儲方式?

我建議使用JSON將數據寫到文本文件https://docs.python.org/3/library/json.html

您可以使用json.dumps方法創建可寫入文件的JSON數據,並使用json.loads方法將文件中的文本轉換回字典中

好吧,既然您的問題要求“一種更有效的數據存儲方式”,我將說是!

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

書架是永久存儲字典並隨時更改/編輯字典的好工具。 我目前正在將它用於我正在進行的一個不一致的bot項目,到目前為止,它很棒。

這是一些使用入門的技巧(直接從我鏈接的頁面中提取)。

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM