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
讓我知道這是否有效。
添加回答
舉報