user1919
user1919

Reputation: 3938

saving a structure of a list with the data in a text file using Python

I have a list of lists of tuples which I want to save in a text file as a string and later read it from another Python script and use ast.literal_eval to transform it from string to list.

My question is if its possible to write in a text file not only the data in the list but the whole structure my list of lists of tuples has.

For example to have a text file like this:

[[(365325.342877, 4385460.998374), (365193.884409, 4385307.899807), (365433.717878, 4385148.9983749995)]]

Does this makes sense?

Upvotes: 0

Views: 536

Answers (2)

kylieCatt
kylieCatt

Reputation: 11039

This sounds like a situation better suited to pickle than writing to a text file and using ast.literal_eval.

>>> import pickle
>>> l = [(1,2),(3,4)]
>>> with open('new_pickle.txt', 'wb') as f:
    pickle.dump(l, f)

>>> ================================ RESTART ================================
>>> import pickle
>>> with open('new_pickle.txt' ,'rb') as f:
    l = pickle.load(f)

>>> l
[(1, 2), (3, 4)]
>>> 

Upvotes: 6

ShadowRanger
ShadowRanger

Reputation: 155363

Writing out the repr will work, so long as all the values are Python built-ins with literal representations (e.g. int, float, str, bytes). But you shouldn't do this; it's limited to Python literals and slower. Use the pickle module, the Python standard for serializing arbitrary data; it's faster, works with types that lack a literal representation, and (often) produces smaller output (particularly if you're using protocols 2 and higher).

Edit: To your concern over reproducibility: pickles reproduce the original structure precisely.

Upvotes: 3

Related Questions