0

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.

Christoph Rackwitz
  • 11,317
  • 4
  • 27
  • 36
Kako Simi
  • 11
  • 2

2 Answers2

2

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')

pyrifo
  • 109
  • 4
0

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
Amin S
  • 546
  • 1
  • 14
  • numpy already has functions for this. the output shown in the question is very likely produced by a numpy array. – Christoph Rackwitz Jan 19 '23 at 10:03
  • True, Just answered this way as a different and classic approach. the numpy way has been already answered. @ChristophRackwitz – Amin S Jan 19 '23 at 10:46