w3resource

How to save a NumPy array to a text file and read it back?

NumPy: I/O Operations Exercise-6 with Solution

Write a NumPy program that saves a NumPy array to a text file with space as the delimiter and then reads it back into a NumPy array.

Sample Solution:

Python Code:

import numpy as np

# Create a NumPy array
data_array = np.array([[1, 2, 3], [4, 5, 6], [7, 8, 9]])

# Define the path to the text file
text_file_path = 'data.txt'

# Save the NumPy array to a text file with space as the delimiter
np.savetxt(text_file_path, data_array, delimiter=' ')

# Read the text file back into a NumPy array
loaded_array = np.loadtxt(text_file_path, delimiter=' ')

# Print the original and loaded NumPy arrays
print("Original NumPy Array:")
print(data_array)

print("\nLoaded NumPy Array from Text File:")
print(loaded_array)

Output:

Original NumPy Array:
[[1 2 3]
 [4 5 6]
 [7 8 9]]

Loaded NumPy Array from Text File:
[[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]]

Explanation:

  • Import NumPy Library: Import the NumPy library to handle arrays.
  • Create NumPy Array: Define a NumPy array with some example data.
  • Define Text File Path: Specify the path where the text file will be saved.
  • Save Array to Text File: Use np.savetxt() to save the NumPy array to a text file, specifying space as the delimiter.
  • Read Text File into NumPy Array: Use np.loadtxt() to read the contents of the text file back into a NumPy array, specifying space as the delimiter.
  • Print Original and Loaded Arrays: Output both the original NumPy array and the loaded array to verify that the data was saved and read correctly.

Python-Numpy Code Editor:

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

Previous: How to read a CSV file with missing values into a NumPy array?
Next: How to save and load a NumPy array to and from a Binary file?

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://www.w3resource.com/python-exercises/numpy/save-a-numpy-array-to-a-text-file-and-read-it-back.php