# Understand numpy.savetxt() for Beginner with Examples – NumPy Tutorial

By | October 16, 2019

numpy.savetxt() function can help us to save numpy data into a txt file (.txt or .csv). In this tutorial, we will write some examples to help numpy beginners to undstand and use it correctly.

## Syntax

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

Save an array to a text file.

## Parameters

fname: the name of text file.

X: numpy 1D or 2D ndarray, this is very important, 3D, 4D can not be saved.

fmt: format the data in X, for example: %d or %10.5f

delimiter: string or character separating columns in fname.

newline: string or character separating lines.

header: string that will be written at the beginning of the file. It is often be used to a comments.

footer: string that will be written at the end of the file.

comments: string that will be prepended to the header and footer strings, you can use #, ;

encoding: the string encoding in fname, it can be utf-8.

Here we will write some examples to show how to use this function.

## Create a 1-D numpy array

import numpy as np

data = np.array([1, 2, 3, 4, 5])
print(data)

## Save 1-D numpy array into txt file

fname= 'data.txt'
np.savetxt(fname, data, fmt = '%d')

Open data.txt, we will find the content in data.txt is:

1
2
3
4
5


From the result, we can find, each element in 1-D array data will be a line in data.txt. For example, 1 in data variable and it will hold a line in data.txt.

If you want to save all elements in data variable into data.txt with  float type, you can do like this.

fname= 'data.txt'
np.savetxt(fname, data, fmt = '%f')

Then the content in data.txt is:

1.000000
2.000000
3.000000
4.000000
5.000000


We can add some comments in our data.txt file to help others to understand our data. We can do like this.

fname= 'data.txt'
footer = 'this is foot tip'
np.savetxt(fname, data, fmt = '%f',header= header, footer= footer)

The content in data.txt is:

# this is header tip
1.000000
2.000000
3.000000
4.000000
5.000000
# this is foot tip


## Save 2-D numpy array to txt file

Here we will save 2-D numpy array into a file, you should notice data in each line of data.txt, the content of each line is 1-D array in 2-D array.

import numpy as np

data = np.array([[1, 2, 3], [4, 5, 6]])
print(data)

fname= 'data.txt'
np.savetxt(fname, data, fmt = '%d')

The content in data.txt is:

1 2 3
4 5 6


## Save 3-D array to txt file

numpy.savetxt() function only allow to save 1-D or 2-D array, if you save 3-D, you will get error. Here is an example.

import numpy as np

data = np.array([[, , ], [, , ]])
print(data)

fname= 'data.txt'
np.savetxt(fname, data, fmt = '%d')

Then you will get error: ValueError: Expected 1D or 2D array, got 3D array instead