What is the savetxt() method in Numpy?

Overview

Numpy https://how.dev/answers/what-is-numpyis an efficient data manipulation library specifically used for higher-dimensional arrays, matrices, and more. It also has a variety of high-level functions to perform mathematical functions on these arrays.

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

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 array
dataArray = np.array([9, 12,19,28,39,44,87,45,85,37,48,99])
# invoking savetxt() to save array as data.txt file
np.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 takes data.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() function
import numpy as np
array = np.array([3,1,0,3,4,5,7,8,5,6,9,2])
print(f"x is:{array}")
# invoking savetxt() function
np.savetxt('data.txt', array, delimiter =',')
a = open("data.txt", 'r+')# open file in read mode
# printing content in data.txt
print("File data: ")
print(a.read())

Explanation

  • Lines 4: We create a Numpy array and assign it to array variable.
  • Line 5: We print the array on the console.
  • Line 7: We invoke np.savetxt() that takes data.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 mode r+. It returns the file descriptor to a variable.
  • Lines 10 and 11: We use a.read() to return content as a string and print it on the console.

Free Resources