I need to write multiple arrays (3,3) on the same file and read them one by one. It’s the first time I use Python. Help me, please
Asked
Active
Viewed 813 times
2 Answers
1
You could use np.savez
:
# save three arrays to a numpy archive file
a0 = np.array([[1,2,3],[4,5,6],[7,8,9]])
a1 = np.array([[11,12,13],[14,15,16],[17,18,19]])
a2 = np.array([[21,22,23],[24,25,26],[27,28,29]])
np.savez("my_archive.npz", soil=a0, crust=a1, bedrock=a2)
# opening the archive and accessing each array by name
with np.load("my_archive.npz") as my_archive_file:
out0 = my_archive_file["soil"]
out1 = my_archive_file["crust"]
out2 = my_archive_file["bedrock"]
https://www.pythonlikeyoumeanit.com/Module5_OddsAndEnds/WorkingWithFiles.html

eugesh
- 111
- 5
0
if you mean an array like this
mylist = [[1,2,3],[4,5,6],[7,8,9]]
the n the solution is like this
with open("fout.txt", "w") as fout:
print(*mylist, sep="\n", file=fout)
to read like this
with open("fout.txt", "r") as fout:
print(fout.read())

student2020
- 13
- 6
-
Thanks but in this way I read it as a string but I need to read it as numpy array to reuse it in other mathematical operations – Maca Jul 27 '20 at 14:09
-
you can simply covert it to nupy array after reading it like that: np_array =np.array(A) – student2020 Jul 28 '20 at 06:53