write arrays to disk

Andre Müller gbs.deadeye at gmail.com
Sun Apr 16 10:03:04 EDT 2017


there are many possible solutions.

You'll need a serialiser to convert the Python object into bytes.
If you wan't to access the data from other applications, you can use json,
xml or other well known formats. Json and XML is in the Python standard
You can also use a database.

As json:
arr = [1, 2, 3, 4]
with open('array.json') as fd:
    json.dump(arr, fd)

with open('array.json') as fd:
    arr = json.load(fd)

With a bytearray:
arr = bytearray([1, 2, 3, 4])
with open('ba.bin', 'wb') as fd:

with open('ba.bin', 'rb') as fd:
    arr = bytearray(fd.read())

Another example with a numpy array:
arr = numpy.array([1, 2, 3, 4], dtype=numpy.int)
with open('array.bin', 'wb') as fd:

with open('array.bin', 'rb') as fd:
    arr = numpy.fromfile(fd, dtype=numpy.int)

What you should not do:

arr = [1, 2, 3, 4]
with open('plain.txt', 'wt') as fd:

with open('plain.txt') as fd:
    arr = eval(fd.read())

If you need to store more data, you should think about a database.


<jorge.conrado at cptec.inpe.br> schrieb am So., 16. Apr. 2017 um 14:29 Uhr:

> Hi,
> I'm new on Python software. I would like to write on disk arrays in
> binary or ascii format. Can someone please help me?
> Thanks,
> Conrado
> --
> https://mail.python.org/mailman/listinfo/python-list

More information about the Python-list mailing list