2

I have a big list of lists like this in Python 3:

array = [[262,231],[123,222],[237272,292]...]

I want to save this in binary in python I tried this:

output = open("pratica3.dat", "wb")
inbytes = bytes(array)
output.write(inbytes)

But this gives an error: TypeError: 'list' object cannot be interpreted as an integer

And if I try to run through the list and save, this gives me annother error of out of range 256

2
  • bytes doesn't work on arbitrary data structures. Try pickle. Commented Mar 15, 2016 at 23:36
  • 1
    Why do you want it to be binary? Could you use json? pickle? Is there any specific format? e.g. the array contains sublists of length 2 that only hold integers? In that case, you can probably get the most minimal file size using numpy. Commented Mar 15, 2016 at 23:42

3 Answers 3

1

I think you're looking for pickle:

import pickle

pickle.dump(array, output) # converts array to binary and writes to output

array = pickle.load(output) # Reads the binary and converts back to list
Sign up to request clarification or add additional context in comments.

Comments

1

To save the array as binary file, you need to open a binary file using open(filename, 'wb'). Otherwise, only using pickle.dump() throws TypeError: file must have 'write' attribute.

So, the code looks like this.

import pickle as pk

#save as binary file
pk.dump(your_array, open(filename, 'wb'))

Comments

1

Try with pickle it will work fine

import pickle  # import pickle

fptr = open("filename", "wb")  # open file in write binary mode
pickle.dump(my_list, ftpt)  # dump list data into file 
fptr.close()  # close file pointer

fptr = open("filename", "rb")  # open file in read binary mode
test_list = pickle.load(fptr)  # read binary data from file and store in list
print(test_list)  # print the data
fptr.close()

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.