3 回答

TA贡献1936条经验 获得超7个赞
如果您的'y.txt'文件包含['I like dogs', 'Go home', 'This is the greatest Ice Cream ever']没有字符串格式的内容,并且在阅读文本行后您希望将列表分配给某个变量,请尝试以下操作:
from ast import literal_eval
with open('y.txt', 'r', encoding = 'utf-8') as f:
b = f.readlines()
print(b) # OUTPUT - ["['I like dogs','Go home','This is the greatest Ice Cream ever']"]
l = literal_eval(b[0])
print(l) # OUTPUT - ['I like dogs', 'Go home', 'This is the greatest Ice Cream ever']
使用上述代码有一个限制——只有当文本文件包含单个列表时,这才有效。如果里面包含多个列表'y.txt',试试这个:
from ast import literal_eval
with open('y.txt', 'r', encoding = 'utf-8') as f:
b = f.readlines()
l = [literal_eval(k.strip()) for k in b]

TA贡献1836条经验 获得超3个赞
列表可以直接从y.txtas中提取
>>> with open('y.txt', 'r') as file:
... line = file.readlines()[0].split("'")[1::2]
...
>>> line
['I like dogs', 'Go home', 'This is the greatest Ice Cream ever']

TA贡献1880条经验 获得超4个赞
如果只有一行包含您的列表作为字符串并且它是第一行,我建议您试试这个
fil = open('y.txt', 'r', encoding="utf-8")
lis = eval(fil.readlines()[0])
现在你应该可以使用 list - lis
让我知道这是否有效。
添加回答
举报