簡體   English   中英

從文本文件讀取列表時,列表不被識別為列表

[英]List not being recognised as a list when read from text file

我正在從txt文件讀取列表,但是當我將它們讀回並保存到變量中時,Python會識別出它包含字符串而不是列表。 有沒有辦法解決?

def makereport():
    with open('quizdb','r') as quizdata:
        for line in quizdata:
            print(line)
            print(line[1])

輸出:

['maths(easy).txt', 'joh17', 'C', 0.0, 0]
'

如您所見,當我按索引位置打印時,它是在打印字符,而不是列表中的實際位置(對象)

除了字符串,您無法從文件中讀取任何內容。 您需要為此使用python庫,例如ast

>>> ast.literal_eval("['maths(easy).txt', 'joh17', 'C', 0.0, 0]")
['maths(easy).txt', 'joh17', 'C', 0.0, 0]

這會將字符串解釋為實際list ,您可以在其中訪問索引:

>>> ast.literal_eval("['maths(easy).txt', 'joh17', 'C', 0.0, 0]")[0]
'maths(easy).txt'

查看jsonpickle以獲得更直觀的數據存儲方式。 通常,最好使用這些方法之一,而不是實際存儲原始字符串表示形式,因為客戶端可以簡單地調用json.loads而不是必須評估文本文件。

暫無
暫無

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

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