How to save a NumPy array to a text file?
Last Updated :
18 Jun, 2021
Let us see how to save a numpy array to a text file.
Method 1: Using File handling
Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function. Below are some programs of the this approach:
Python3
import numpy
List = [ 1 , 2 , 3 , 4 , 5 ]
Array = numpy.array( List )
print ( 'Array:\n' , Array)
file = open ( "file1.txt" , "w+" )
content = str (Array)
file .write(content)
file .close()
file = open ( "file1.txt" , "r" )
content = file .read()
print ( "\nContent in file1.txt:\n" , content)
file .close()
|
Array:
[1 2 3 4 5]
Content in file1.txt:
[1 2 3 4 5]
Python3
import numpy
List = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
Array = numpy.array( List )
print ( 'Array:\n' , Array)
file = open ( "file2.txt" , "w+" )
content = str (Array)
file .write(content)
file .close()
file = open ( "file2.txt" , "r" )
content = file .read()
print ( "\nContent in file2.txt:\n" , content)
file .close()
|
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Content in file2.txt:
[[1 2 3]
[4 5 6]
[7 8 9]]
Using NumPy functions
After creating the array, the
numpy.savetxt()
function can be used to save the array into a text file. Below are some programs of this approach.
Python3
import numpy
List = [ 1 , 2 , 3 , 4 , 5 ]
Array = numpy.array( List )
print ( 'Array:\n' , Array)
numpy.savetxt( "file1.txt" , Array)
content = numpy.loadtxt( 'file1.txt' )
print ( "\nContent in file1.txt:\n" , content)
|
Array:
[1 2 3 4 5]
Content in file1.txt:
[1. 2. 3. 4. 5.]
Python3
import numpy
List = [[ 1 , 2 , 3 ], [ 4 , 5 , 6 ], [ 7 , 8 , 9 ]]
Array = numpy.array( List )
print ( 'Array:\n' , Array)
numpy.savetxt( "file2.txt" , Array)
content = numpy.loadtxt( 'file2.txt' )
print ( "\nContent in file2.txt:\n" , content)
|
Array:
[[1 2 3]
[4 5 6]
[7 8 9]]
Content in file2.txt:
[[1. 2. 3.]
[4. 5. 6.]
[7. 8. 9.]]
Please Login to comment...