w3resource

NumPy: Save a NumPy array to a text file

NumPy: Array Object Exercise-32 with Solution

Write a NumPy program to save a NumPy array to a text file.

Sample Solution:

Python Code:

# Importing the NumPy library with an alias 'np'
import numpy as np

# Generating an array using arange() from 1.0 to less than 2.0 with step 36.2
a = np.arange(1.0, 2.0, 36.2)

# Saving the array 'a' into a file named 'file.out' with ',' as a delimiter using savetxt()
np.savetxt('file.out', a, delimiter=',')

Explanation:

In the above code –

a = np.arange(1.0, 2.0, 36.2): This line creates a NumPy array ‘a’ using the np.arange() function with a start value of 1.0, an end value of 2.0, and a step size of 36.2. However, since the end value (2.0) is smaller than the start value plus the step size (1.0 + 36.2), the resulting array will only contain the start value: [1.0].

np.savetxt('file.out', a, delimiter=','): This line saves the NumPy array ‘a’ to a file named 'file.out' using a comma delimiter. In this case, the content of 'file.out' will be "1.0" as there is only one element in the array.

Python-Numpy Code Editor:

Previous: Write a NumPy program to get the values and indices of the elements that are bigger than 10 in a given array.
Next: Write a NumPy program to find the memory size of a NumPy array.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://198.211.115.131/python-exercises/numpy/python-numpy-exercise-32.php