What is the savetxt() method in Numpy?
Overview
Numpy
The savetxt() method is used to save an array into a text file.
Syntax
Let's view the syntax of the function:
numpy.savetxt(fname,X,fmt='%.18e',delimiter=' ',newline='\n',header='',footer='',comments='# ',encoding=None)
savetxt method syntax
Parameters
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 compressedgzipformat.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 inputXand 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'.
Return value
It does not return any value. Instead, exceptions are thrown.
Code example 1
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')
Explanation
- Line 3: We create a random NumPy array and assign it to
dataArray. - Line 5: We invoke
np.savetxt()that takesdata.txt, the above-created array and multi-string format to the same file.
Code example 2
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())
Explanation
- Lines 4: We create a Numpy array and assign it to
arrayvariable. - Line 5: We print the array on the console.
- Line 7: We invoke
np.savetxt()that takesdata.txt(the above-created NumPy array and file content delimiter). - Line 8: We invoke
open()to include data.txt in the current program thread in additional reading moder+. It returns the file descriptor toavariable. - Lines 10 and 11: We use
a.read()to return content as a string and print it on the console.