0

I have a list including 4000 elements in python which each of its elements is an object of following class with several values.

class Point:
     def __init__(self):
        self.coords = []
        self.IP=[]
        self.BW=20
        self.status='M'
     def __repr__(self):
         return str(self.coords)

I do not know how to save this list for future uses. I have tried to save it by open a file and write() function, but this is not what I want. I want to save it and import it in next program, like what we do in MATLAB that we can save a variable and import it in future

2
  • You could use pickle, except it's awful and insecure, or make your own serialization method. Commented Oct 15, 2013 at 17:18
  • title should probably really be 'how to save classes in python'. simple lists can be done many different ways. Commented Oct 15, 2013 at 17:58

3 Answers 3

2

pickle is a good choice:

import pickle

with open("output.bin", "wb") as output:
    pickle.dump(yourList, output)

and symmetric:

import pickle

with open("output.bin", "rb") as data:
    yourList = pickle.load(data)

It is a good choice because it is included with the standard library, it can serialize almost any Python object without effort and has a good implementation, although the output is not human readable. Please note that you should use pickle only for your personal scripts, since it will happily load anything it receives, including malicious code: I would not recommend it for production or released projects.

Sign up to request clarification or add additional context in comments.

Comments

1

This might be an option:

f = open('foo', 'wb')

np.save(f, my_list)

for loading then use

data = np.load(open('foo'))

if 'b' is not present in 'wb' then the program gives an error: TypeError: write() argument must be str, not bytes

"b" for binary makes the difference.

Comments

0

Since you say Matlab, numpy should be an option.

f = open('foo', 'w')
np.save(f, my_list)

# later
data = np.load(open('foo'))

Of course, it'll return an array, not a list, but you can coerce it if you really want an array...

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.