如何将“stringized”python对象从文件解析回python对象?

2024-09-28 20:59:58 发布

您现在位置:Python中文网/ 问答频道 /正文

我试图解析一个包含python对象的字符串表示的文件。如

outfile = open("out.txt", "w")
example_string_tuple = (u'bretagne tr\xe9minou 23archiefdingen', u'chicago, il')

# Instead of doing something like this:
outfile.write("\t".join(example_string_tuple).encode("utf-8"))

# I just did this:
outfile.write(str(example_string_tuple))

所以现在在我的文本文件中,我有这样的行

(u'bretagne tr\xe9minou 23archiefdingen,伊利诺伊州芝加哥)

注意,unicode不是utf-8,而是python的本机编码。在

如何正确地将这些行解析回原来的元组(而不弄乱编码)?(我使用的是python2.7)


Tags: 文件对象字符串编码stringexampleopenthis