Numpy
The savetxt()
method is used to save an array into a text file.
Let's view the syntax of the function:
numpy.savetxt(fname,X,fmt='%.18e',delimiter=' ',newline='\n',header='',footer='',comments='# ',encoding=None)
It takes the following argument values:
fname
: This can be a file name or filehandle. If the file name ends with .gz
, it has the ability to save files in compressed gzip
format.X
: This is the data to save in a text file.fmt='%.18e'
: This is the string or sequence of strings. It is also used for complex input X
and multiformat strings.delimiter=' '
: This is the character or string separating columns.newline='\n'
: This is used to separate strings, characters, or string separating lines.header=' '
: This is used to specify whether the string is written at the beginning of the file or not.footer=' '
: This is used to specify whether the string is written at the end of the file or not.comments='#'
: This is used for commenting purposes.encoding=None
: This is the encoding scheme that is used to encode the output file. It can be 'bytes'
or 'latin1'
.It does not return any value. Instead, exceptions are thrown.
Let's view the code example below:
import numpy as np# creating a numpy arraydataArray = np.array([9, 12,19,28,39,44,87,45,85,37,48,99])# invoking savetxt() to save array as data.txt filenp.savetxt('data.txt', dataArray, fmt='%.18e')
dataArray
.np.savetxt()
that takes data.txt
, the above-created array and multi-string format to the same file.Let's look at another coding example below:
# Python program explaining# savetxt() functionimport numpy as nparray = np.array([3,1,0,3,4,5,7,8,5,6,9,2])print(f"x is:{array}")# invoking savetxt() functionnp.savetxt('data.txt', array, delimiter =',')a = open("data.txt", 'r+')# open file in read mode# printing content in data.txtprint("File data: ")print(a.read())
array
variable. np.savetxt()
that takes data.txt
(the above-created NumPy array and file content delimiter).open()
to include data.txt in the current program thread in additional reading mode r+
. It returns the file descriptor to a
variable.a.read()
to return content as a string and print it on the console.