I stored array to file with:
file = open("file1.txt", "w ")
# Saving the 2D array in a text file
content = array2d
file.write(str(content))
file.close()
and now I have to use that array that looks like this in file (this is just shorten):
[[[ 253 122]
[ 253 121]
[ 253 121]
...
[1027 119]
[1027 120]
[1028 120]]
[[ 252 122]
[ 253 122]
[ 253 122]
...
[1067 573]
[1067 573]
[1067 573]]]
I have to open this file and store array in new one to access all integer elements like I can before saving.
I tried with:
text_file = open("file1.txt", "r")
data = []
data = text_file.read()
text_file.close()
print(data[0])
and as first element data[0] gives me [ and it should be 253.
CodePudding user response:
It gives you "[" because it is purely a text file, thus the first character of the string-array is just "[". I would suggest using numpy.save for saving arrays: https://numpy.org/doc/stable/reference/generated/numpy.save.html and numpy.load for loading arrays: https://numpy.org/doc/stable/reference/generated/numpy.load.html
Simply, numpy.save('name_of_file_to_save', array_to_save) And to load: numpy.load('name_of_file_to_save')
CodePudding user response:
Simple way using pickle
import pickle
file = open("file1.txt", "wb") #file
content = [[[ 253 , 122],[ 253 , 121],[1067 ,573]]]
pickle.dump(content, file) #saving
file.close()
file = open("file1.txt", "rb") #file
data= pickle.load(file) #loadinga file
file.close()
print(data[0]) #e.x