I have this list in a txt file:
[1, "hello", {"Name": "Tom"}, [2, 3, "hello_hello"], (800, 600)]
There are an int, a str, a dict, a list and a tuple (not that it was really the matter).
I'd like to read this like this was a list (as it really is) not like one string.
I'd like to get a result like:
elem[0] = 1
elem[1] = "hello"
elem[2] = {"Name": "Tom"}
elem[3] = [2, 3, "hello_hello"]
elem[4] = (800,600)
Also it would be really nice if the dictionary evaluated eval() immediately, but that's not really the point.
解决方案
As indicated by @AvinashRaj in the comments, you can use the ast module (ast: Abstract Syntax Trees):
import ast
print ast.literal_eval('[1, "hello", {"Name": "Tom"}, [2, 3, "hello_hello"], (800, 600)]')
Output:
[1, 'hello', {'Name': 'Tom'}, [2, 3, 'hello_hello'], (800, 600)]
This should be the exact result (elem) you are expecting.
本文介绍了一种使用Python的ast模块来解析包含多种数据类型(如整数、字符串、字典、列表和元组)的txt文件的方法。通过使用ast.literal_eval函数,可以将这些数据转换为Python原生的数据结构。
1181

被折叠的 条评论
为什么被折叠?



