How to read array of integer list stored in text file in Python?

Viewed 104

I wrote a text file that contains list of integers like below

cords = [[385, 24], [695, 32], [1010, 106], [1122, 245]]
f = open('ref_points.txt', 'w')
f.write(str(cords))
f.close()

I want to read back this text file and get the list of integers. I know when we read contents, it is str, and need processing to store in list. I would like to know if there is any better and efficient way of doing it.

Thanks

2 Answers

You can use the pickle module and store the data as binary data, this way you have to not perform any type conversions. pickle already comes with python so you do not have to install anything either.

import pickle
coords = [[385, 24], [695, 32], [1010, 106], [1122, 245]]
f = open("points.bin", "wb")
pickle.dump(coords, f);
f.close();

# you can read it like this
f = open("points.bin", "wb")
coords = pickle.load(f) # here coords is a list so you do not have to convert anything
f.close()

also as @Marcin_Orlowski mentioned in the comments, a better way to open files will be to do so:

with open("somefile.txt") as f:
    # now you can use f for the file

this way you dont have to call f.close() either.

You can use the module pickle to safe class objects. Convert your data into objects and put all your objects into one holder object and then safe this object with pickle.

example:

import pickle

class Cords:
    def __init__(self, x, y)
        self.x = x
        self.y = y

class Data():
    def __init__(self, list)
        self.list = list

cord1 = Cords(385, 24)
cord2 = Cords(695, 32)

list_of_data = []
list_of_data.append(cord1, cord2)

data = Data(list_of_data)

pickle.dump(data, open("path/dataname.data", "wb"))    #saves the data
loaded_data = pickle.load(open("path/dataname.data", "rb"))    #loads data

the ending could be everything .data .src .everything

wb = write binary rb = read binary

The usage of class attributes gives a lot of andvantages in accessing and further process your cords. And that the loaded object already exist as a classobject makes it obsolete to do any converting stuff because its already in a good accessible form.

Related