conradlee
conradlee

Reputation: 13705

How to parse "stringified" python objects from file back into python objects?

I'm trying to parse a file that includes the string representations of python objects. As in

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))

So now in my textfile I have lines that look like this

(u'bretagne tr\xe9minou 23archiefdingen', u'chicago, il')

Note that the unicode is not in utf-8, it's in python's native encoding.

How do I properly parse these lines like that back into the original tuples (without messing up the encoding)? (I'm using python 2.7)

Upvotes: 0

Views: 196

Answers (1)

Ignacio Vazquez-Abrams
Ignacio Vazquez-Abrams

Reputation: 799102

>>> ast.literal_eval("""(u'bretagne tr\xe9minou 23archiefdingen', u'chicago, il')""")
(u'bretagne tr\xe9minou 23archiefdingen', u'chicago, il')

But use JSON next time.

Upvotes: 2

Related Questions