NumPy: Save a NumPy array to a text file
Save Array to Text File
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:
What is the difficulty level of this exercise?
Test your Programming skills with w3resource's quiz.
- Weekly Trends and Language Statistics
- Weekly Trends and Language Statistics