In this Python NumPy tutorial, we will learn how do we save the array to a text file in NumPy Python. With the Python NumPy savetext function, we will cover these topics.
- Python numpy savetxt format
- Python numpy savetxt header
- Python numpy savetxt append
- Python numpy savetxt 3d array
- Python numpy savetxt fmt
- Python numpy savetxt multiple arrays
- Python numpy savetxt csv
- Python numpy savetxt string
- Python numpy savetxt example
- Python np.savetxt header without #
- Python numpy savetxt mismatch between array dtype
Python numpy savetxt
- In this section, we will discuss how to save a numpy array into a text file in Python.
- To save a numpy array to a text file we can easily use the numpy.savetxt() method. In Python, this method is available in the NumPy package module and it saves array numbers in CSV file format.
- This method takes two parameters which are file name and data that we want to save in a text file.
Syntax:
Let’s have a look at the Syntax and understand the working of numpy.savetxt() function
numpy.savetxt
(
fname,
X,
fmt='%.18e',
delimiter=' ',
newline='\n',
header=' ',
footer=' ',
comments= '#',
encoding=None
)
- It consists of a few parameters
- fname: This parameter indicates the filename and it is basically used if a file ends with gz and the file is automatically saved in compressed gzip.
- X: It is an input array and is used to store data in a text file.
- fmt: By default, it takes ‘%.18e’ and it is also used for multiformat strings.
- delimiter: This is used for separating columns and it is an optional parameter.
- newline: This parameter is used to separate the string (line separator).
- header: This parameter indicates the string can be written at the starting of the file.
- footer: It represents the string that can be written at the end of the file.
- comments: This parameter uses the ‘#’ symbol for commenting on a selected section.
- encoding: By default, it takes none value.
Example:
Let take an example and check how to save a numpy array into a text file
Source Code:
import numpy as np
new_array = np.array([24, 15,27,38,15,16,25,38,485,15,16,15])
result=np.savetxt('test9.txt', new_array, delimiter=',', fmt='%d')
print(result)
In the following given code, we imported the numpy library and then declare a variable named ‘new_array’ for array and assigned values. Next, we will try to print the values in a text file by using the numpy.savetxt() function to store the array elements into the text file.
Here is the implementation of the following given code
Read: Python NumPy Normalize + Examples
Python numpy savetxt format
- In this program, we will discuss how to use the format option in Python Numpy savetxt() function.
- In this example, we are going to use the numpy.savetxt() function and it will help the user to save the numpy array into a text file along with that we have used the format parameter in the function.
- This parameter indicates the sequence of formats a single specifier is ‘%.4e’ and by default its takes ‘%.18e’ value.
Syntax:
Here is the Syntax of numpy.savetxt() function
numpy.savetxt
(
fname,
X,
fmt='%.18e',
delimiter=' ',
newline='\n',
header=' ',
footer=' ',
comments= '#',
encoding=None
)
Source Code:
import numpy as np
new_array = np.array([17, 26,37,38,49,94,78,45,85,37,48,98])
new_output= np.savetxt('test9.txt', new_array, fmt='%.18e')
print(new_output)
Here is the Screenshot of the following given code
Text file Screenshot
Read: Python NumPy Random [30 Examples]
Python numpy savetxt header
- In this section, we will discuss how to use the header parameter in the numpy savetxt() function.
- Here we can use the header parameter in numpy.savetxt() function. This parameter indicates the input string can be written at the starting of the file. In this example, we have given the header value= “Integer values”. Once you will print ‘final_result’ then the output will display the values in the text file along with the header name.
Source Code:
import numpy as np
new_values = np.array([56, 156,89,27,38,45,89,189,234,356,897,456])
final_result=np.savetxt("test9.txt", new_values, delimiter=",", header="Integer values")
print(final_result)
Here is the Output of the following given code
Here is the output of the text file
Python numpy savetxt append
We had already covered this topic in Python NumPy add an article. You can get all the information regarding Numpy savetxt append.
Python numpy savetxt 3d array
- In this section, we will discuss how to save a 3-dimension array into a text file by using the Python numpy.savetxt() function.
- Firstly, we will create a simple 3-d array and assign integer values. Next we will declare a variable ‘final_result’ and use the np.savetxt() function.Within this function, we have assigned an array, text file as an argument.
- Now we will execute this program and check how to save the numpy 3-d array to a text file.
Example:
import numpy as np
new_arr = np.array([[[45, 78],
[19, 23]],
[[78, 56],
[98, 12]]])
print("Size of array:",new_arr.ndim)
final_result=np.savetxt("test9.txt", new_arr, delimiter=",",fmt='%d')
print("Save array into text file:",final_result)
Here is the implementation of the following given code
As you can see in the Screenshot the output displays the ValueError: “Expected 1D or 2d array, got 3d array instead”. This error may occur because as per the numpy.savetxt documentation the data to be saved to a text file only 1d and 2d arrays.
Read: Python NumPy max with examples
Python numpy savetxt fmt
- In this Program, we will discuss how to use the fmt parameter in Python numpy.savetxt() function.
- In this example, we are going to use the numpy.savetxt() function and with the help of the fmt parameter we can easily get the solution in integer, float, or string order.
- By default it takes fmt=’%.18e’ but in this program, we will assign ‘%1.4e’ value as an argument. This value represents th exponential notation in a text file.
Syntax:
Here is the Syntax of Python numpy.savetxt() function
numpy.savetxt
(
fname,
X,
fmt='%.18e',
delimiter=' ',
newline='\n',
header=' ',
footer=' ',
comments= '#',
encoding=None
)
Example:
Let take an example and check how to use the fmt parameter in Python numpy.savetxt() function
import numpy as np
new_elements = np.array([13,23,45,6,7,8,9])
print("Size of array:",new_elements.ndim)
output=np.savetxt("test9.txt", new_elements, delimiter=",",fmt='%1.4e')
print("Save array into text file:",output)
In the above code, we imported the numpy library and then initialize an array by using the np.array() function. After that, we have used the numpy.savetxt() function and assign ‘fmt’ as an argument. Once you will print ‘output’ then the result will display the new exponential values.
Here is the execution of the following given code
Text file Screenshot
Read: Python NumPy shape with examples
Python numpy savetxt multiple arrays
- In this section, we will discuss how to save multiple arrays in a text file by using numpy.savetxt() function.
- To perform this particular task, firstly we will create multiple arrays by using the np.array() function. Next, we are going to use the numpy.savetxt() function and within this method, we have passed multiple input arrays. Once you will print ‘result’ then the output will display the arrays in a text file.
Source Code:
import numpy as np
new_elements = np.array([13,23,45,6,7,8,9])
new_elements2 = np.array([16,27,36,56,78,16,18])
new_elements3 = np.array([77,66,289,198,456,901,238])
result= np.savetxt('test9.txt',(new_elements,new_elements2,new_elements3),fmt='%d')
print(result)
You can refer to the below Screenshot
Output
Read: Python reverse NumPy array
Python numpy savetxt csv
- In this Program, we will learn how to save a numpy array into a CSV file in NumPy Python.
- In Python, a CSV file is used to store the tabular data and it must be saved with the. CSV file extension. In this example, we have to store the numpy array into a CSV file.
- To do this task first, we have to create an empty CSV file. Next, we have to create a program in which we have to initialize an array by using the np.array() function. In this method, we have specified the file format, delimiter, character to get the result.
Example:
import numpy as np
new_array = np.array([25,78,98,56,96,178,29])
result= np.savetxt('final.csv',new_array,fmt='%d')
print(result)
Here is the execution of the following given code
Output
As you can see in the Screenshot the output displays the array.
Read: Python NumPy empty array
Python numpy savetxt string
- Here we can see how to use the string format in Python numpy.savetxt() function.
- By using the numpy.savetxt() function we can easily solve this problem. in this program, we will assign ‘%s’ value as an argument. This value represents the string values in a text file.
Syntax:
Here is the Syntax of numpy.savetxt() function
numpy.savetxt
(
fname,
X,
fmt='%.18e',
delimiter=' ',
newline='\n',
header=' ',
footer=' ',
comments= '#',
encoding=None
)
Example:
Let’s take an example and check how to use the string formatter in numpy.savetxt() method
import numpy as np
values = np.array(['25','78','98','56','96','178','29'])
new_output= np.savetxt('test9.txt',values, delimiter=" ",fmt="%s")
print(new_output)
In the following given code, we will import the NumPy library and then create an array by using the np.array() function. After that, we declared a variable ‘new_output’ and assign a numpy.savetxt() function. Within this function, we have used the string fmt ‘s’ as an argument.
Output
Read: Python NumPy Average with Examples
Python numpy savetxt example
- In this Program we will discuss how to use the numpy.savetxt() function in NumPy array Python.
- In Python, this method is available in the NumPy package module and it saves array numbers in text file format.
- In this example, we have used the header, delimiter parameter in numpy.savetxt() function. Once you will print ‘new_output’ then the result will display the array number with the header name.
Example:
import numpy as np
new_values = np.array([12, 36,89,67,89,98,190,38,485,15,16,15])
new_output=np.savetxt('test9.txt', new_values, delimiter=',', fmt='%d',header="New elements")
print(new_output)
Here is the Screenshot of the following given code
Read: Python NumPy square with examples
Python np.savetxt header without #
- In this Program, we will discuss how to use the without # parameter for commenting particular section in NumPy Python.
- To do this task we are going to use the np.savetxt() method and within this function, we will use the comments parameter that indicates if you want to add some content to a particular section.
Source Code:
import numpy as np
elements = np.array([78, 67,92,389,198,234,190,38,485,802,983,167])
final_output=np.savetxt('test9.txt', elements, delimiter=',', fmt='%d',header="New Numbers",comments='Add Numbers')
print(final_output)
Here is the execution of the following given code
Output Screenshot
As you can see in the Screenshot the output displays the array.
Read: Python NumPy to list with examples
Python numpy savetxt mismatch between array dtype
- In this section, we will discuss how to solve the error numpy savetxt mismatch between array type in Python.
- In this example, we have created an array by using the np.array() function that contains integer values. Next, we have used the numpy.savetxt() function and assign the text file.
Example:
import numpy as np
new_values = np.array([563,344,67,8,903,2]),np.array([32,34,56,7,8])
final_output=np.savetxt('test9.txt', new_values)
print(final_output)
Here is the Screenshot of the following given code
As you can see in the Screenshot the output displays the error “Mismatch between array type and format specifier”. This error occurs because we have not used the same shape and size array. In numpy.savetxt() function, the array must have the same size and shape.
Solution:
In this example, we have just created a simple array with the same size and used the fmt=%d as an argument in numpy.savetxt() function.
Source Code:
import numpy as np
new_values = np.array([563,344,67,8,903,2]),([32,34,56,7,8,16])
final_output=np.savetxt('test9.txt', new_values,fmt='%d')
print(final_output)
Here is the Output of the following given code
Also, take a look at some more tutorials on Python NumPy.
- Python NumPy where with examples
- Python NumPy log + Examples
- Python NumPy linspace + Examples
- Python NumPy matrix + Examples
- Python NumPy genfromtxt() – Complete Tutorial
- How to Convert NumPy Array to List in Python
So, in this tutorial, we have learned how do we save the array to a text file in NumPy Python. Additionally, we have also covered these topics.
- Python numpy savetxt format
- Python numpy savetxt header
- Python numpy savetxt append
- Python numpy savetxt 3d array
- Python numpy savetxt fmt
- Python numpy savetxt multiple arrays
- Python numpy savetxt csv
- Python numpy savetxt string
- Python numpy savetxt example
- Python np.savetxt header without #
- Python numpy savetxt mismatch between array dtype
I am Bijay Kumar, a Microsoft MVP in SharePoint. Apart from SharePoint, I started working on Python, Machine learning, and artificial intelligence for the last 5 years. During this time I got expertise in various Python libraries also like Tkinter, Pandas, NumPy, Turtle, Django, Matplotlib, Tensorflow, Scipy, Scikit-Learn, etc… for various clients in the United States, Canada, the United Kingdom, Australia, New Zealand, etc. Check out my profile.