Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

what is the best way to save tuples in python

Tags:

python

I have a function which returns a tuple which includes numbers, strings and arrays.For example, (1, 2, 3, [[1,2,3],[4,5,6]], ['a','b','c']). I need to run my function 100 times and save all the results. I'm thinking of save each result as a text file. So I can have 100 *.txt fils like this:

my number1: 1
my number2: 2
my number3: 3
My array:   [[1,2,3],[4,5,6]]
My Names:   ['a','b','c']

How to write the python code?

Is there better way to save the results for easy data re-visit in future?

like image 522
Rosy Avatar asked Jan 29 '16 17:01

Rosy


1 Answers

yes, you can import pickle and use pickle.dump() and pickle.load() to read and write to a file.

Here is how you would write it to a file:

data = (1, 2, 3, [[1,2,3],[4,5,6]], ['a','b','c'])
with open('data.pickle', 'wb') as f:
    pickle.dump(data, f)

To read it back in:

with open('data.pickle', 'rb') as f:
     data = pickle.load(f)
like image 191
rbp Avatar answered Oct 11 '22 12:10

rbp