这似乎是一个简单的问题,但我已经在网上查找了,所以我们在这里找不到任何东西......
我有一个包含此信息的文本文件:
[['AX34 GFV','Name: John Smith1, Address: x, Number: x'],['AX34 ABC','Name: John Smith2, Address: x, Number: x'],['UH23 HUH','Name: John Smith3, Address: x, Number: x'],['ER54 SDR','Name: John Smith4, Address: x, Number: x'],['FE54 VMR','Name: John Smith5, Address: x, Number: x'],['23FX SDA','Name: John Smith6, Address: x, Number: x'],['AS23 JAS','Name: John Smith7, Address: x, Number: x']]
我想要做的就是读取这些数据,并将其作为列表而不是字符串导入。目前,这就是我所拥有的......
details = open("details.txt","r")
details = details.read()
details = list(details)
print(details)
但这需要获取数据的每个字母,并将其作为列表生成...任何解决此问题的简单函数?
答案 0 :(得分:0)
也许你想要这个:
list = []
details = open("details.txt", "r")
line = details.readline()
while(line != ''):
list.append(line)
line = details.readline()
print(list)
details.close()
答案 1 :(得分:0)
我不太确定这只是一条线还是单独的线。
但请尝试.append()
答案 2 :(得分:0)
如果您将Python代码(如此列表)作为字符串,则可以通过eval函数运行它:
>>> eval('[1, "2"]')
[1, '2']
它将返回已评估的Python表达式。 但要小心这样,文件中的代码将被执行。确保没有不安全的用户数据!
答案 3 :(得分:0)
>>> import ast
>>> x = "[['AX34 GFV','Name: John Smith1, Address: x, Number: x'],['AX34 ABC','Name: John Smith2, Address: x, Number: x'],['UH23 HUH','Name: John Smith3, Address: x, Number: x'],['ER54 SDR','Name: John Smith4, Address: x, Number: x'],['FE54 VMR','Name: John Smith5, Address: x, Number: x'],['23FX SDA','Name: John Smith6, Address: x, Number: x'],['AS23 JAS','Name: John Smith7, Address: x, Number: x']] "
>>> ast.literal_eval(x)
[['AX34 GFV', 'Name: John Smith1, Address: x, Number: x'], ['AX34 ABC', 'Name: John Smith2, Address: x, Number: x'], ['UH23 HUH', 'Name: John Smith3, Address: x, Number: x'], ['ER54 SDR', 'Name: John Smith4, Address: x, Number: x'], ['FE54 VMR', 'Name: John Smith5, Address: x, Number: x'], ['23FX SDA', 'Name: John Smith6, Address: x, Number: x'], ['AS23 JAS', 'Name: John Smith7, Address: x, Number: x']]
安全地评估表达式节点或Unicode或Latin-1编码 包含Python表达式的字符串。提供的字符串或节点可以 只包含以下Python文字结构:字符串, 数字,元组,列表,dicts,布尔值和无。
答案 4 :(得分:0)
试试这个:
details = open("details.txt","r")
details = eval(details.read())
print(details)