Python读取文件,读取到的是str类型的内容,如果文件中是一个tuple、list或dict,无法直接使用,需要怎么转化呢?
举个例子:
b.txt的内容为[1,2,3]
with open("d:\\document\\test\\b.txt") as fp:
content = fp.read()
print(content)
print(type(content))
content.append(4)

读出来是str类型,不能直接调用list的append()方法。
要转化为对应的python类型,可以使用eval()方法
with open("d:\\document\\test\\b.txt") as fp:
content = fp.read()
print(content)
print(type(content))
content = eval(content)
content.append(4)
print(content)
print(type(content))

本文介绍如何在Python中从文件读取tuple、list或dict等数据结构,并使用eval()方法将其转换为相应的Python类型,以便进行进一步的处理和操作。


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



