Home » Python NumPy Savetxt with examples

Python NumPy Savetxt with examples

You can use the NumPy savetxt function to save arrays in txt format with different delimiters.

NumPy savetxt function will work with 1D and 2D arrays, the numpy savetxt also saves array elements in csv file format

Syntax:

First lets look at the syntax for numpy.savetxt()

numpy.savetxt(fname, X, fmt='%.18e', delimiter=' ', newline='\n', header='', footer='', comments='# ', encoding=None)

Parameters:

  • fname : If the filename ends in .gz, the file is automatically saved in compressed gzip format. loadtxt understands gzipped files transparently.
  • X : means 1D or 2D array and it is used to store array data in a text file.
  • fmt : A single format (%10.5f), a sequence of formats, or a multi-format string,
  • delimiter : String or character separating columns.
  • newline : String or character separating lines.
  • header : String that will be written at the beginning of the file.
  • footer : String that will be written at the end of the file.
  • comments : comments parameter uses symbol ‘#’ to comment on a particular section. In some versions header and footer are by default assigned as comments.
  • encoding : Encoding used to encode the output file. Does not apply to output streams.

Code

# savetxt() function
import numpy as np
  
x = np.arange(0, 12, 1)
print("x is:")
print(x)
  
# X is an array
c = np.savetxt('np1.txt', x, delimiter =', ')   
myfile = open("np1.txt", 'r')# open file in read mode
  
print("the file contains:")
print(myfile.read())

This will display the following

>>> %Run npsavetxt1.py
x is:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
the file contains:
0.000000000000000000e+00
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
5.000000000000000000e+00
6.000000000000000000e+00
7.000000000000000000e+00
8.000000000000000000e+00
9.000000000000000000e+00
1.000000000000000000e+01
1.100000000000000000e+01

fmt paramaeter

Lets look at the fmt parameter

# savetxt() function
import numpy as np
  
x = np.arange(0, 12, 1)
print("x is:")
print(x)
  
# X is an array
c = np.savetxt('np1.txt', x, delimiter =', ', fmt='%1.4e')   
myfile = open("np1.txt", 'r')# open file in read mode
  
print("the file contains:")
print(myfile.read())

This will display the following

>> %Run npsavetxt1.py
x is:
[ 0 1 2 3 4 5 6 7 8 9 10 11]
the file contains:
0.0000e+00
1.0000e+00
2.0000e+00
3.0000e+00
4.0000e+00
5.0000e+00
6.0000e+00
7.0000e+00
8.0000e+00
9.0000e+00
1.0000e+01
1.1000e+01

 

You may also like

Leave a Comment

This website uses cookies to improve your experience. We'll assume you're ok with this, but you can opt-out if you wish. Accept Read More