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:
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.
For more Practice: Solve these Related Problems:
- Save a NumPy array to a text file using a custom delimiter and verify the contents by reloading the file.
- Create a function that writes an array to a text file with specific formatting for each element.
- Handle large arrays by measuring the time taken to save and load the data from the text file.
- Compare the output file with the original array by reading line by line and checking for consistency.
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.