简体   繁体   English

从文本文件读取列表时,列表不被识别为列表

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

I am reading lists from a txt file but when I read them back in and saved to a variable Python recognizes it has a string and not a list. 我正在从txt文件读取列表,但是当我将它们读回并保存到变量中时,Python会识别出它包含字符串而不是列表。 Is there any way around this? 有没有办法解决?

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

Output: 输出:

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

As you can see when I print by index position it is printing the character and not the actual position(object) in the list 如您所见,当我按索引位置打印时,它是在打印字符,而不是列表中的实际位置(对象)

You cannot read in anything from a file other than strings. 除了字符串,您无法从文件中读取任何内容。 You need to use a python library for that, like ast : 您需要为此使用python库,例如ast

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

This will interpret the string as an actual list , where you can access indices: 这会将字符串解释为实际list ,您可以在其中访问索引:

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

Look into json or pickle for more intuitive ways for storing data. 查看jsonpickle以获得更直观的数据存储方式。 It is generally better to use one of these methods rather than actually storing the raw string representation, as clients can simply call json.loads rather than having to evaluate your text file. 通常,最好使用这些方法之一,而不是实际存储原始字符串表示形式,因为客户端可以简单地调用json.loads而不是必须评估文本文件。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM