w3resource

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.


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.

Go to:


PREV : Elements >10 & Their Indices
NEXT : Memory Size of Array


Python-Numpy Code Editor:

Have another way to solve this solution? Contribute your code (and comments) through Disqus.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.