w3resource

NumPy: Save a given array to a text file and load it

NumPy: Basic Exercise-37 with Solution

Write a NumPy program to save a given array to a text file and load it.

Sample Solution :

Python Code :

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

# Importing the 'os' module for operating system-dependent functionality
import os

# Creating a NumPy array 'x' with integers from 0 to 11 and reshaping it to a 4x3 matrix using np.arange() and .reshape()
x = np.arange(12).reshape(4, 3)

# Printing a message indicating the original array 'x'
print("Original array:")
print(x)

# Creating a string 'header' containing column names 'col1 col2 col3'
header = 'col1 col2 col3'

# Saving the array 'x' into a text file named 'temp.txt' using np.savetxt()
# Specifying the format as "%d" (integer) and including a header with column names
np.savetxt('temp.txt', x, fmt="%d", header=header)

# Printing a message indicating the content of the text file after loading
print("After loading, content of the text file:")

# Loading the data from 'temp.txt' into the variable 'result' using np.loadtxt()
result = np.loadtxt('temp.txt')

# Printing the loaded data 'result' from the text file
print(result) 

Sample Output:

Original array:
[[ 0  1  2]
 [ 3  4  5]
 [ 6  7  8]
 [ 9 10 11]]
After loading, content of the text file:
[[  0.   1.   2.]
 [  3.   4.   5.]
 [  6.   7.   8.]
 [  9.  10.  11.]]                         

Explanation:

In the above code -

The ‘x = np.arange(12).reshape(4, 3)’ statement creates a 1D array with elements ranging from 0 to 11, then reshapes it into a 2D array 'x' of shape (4, 3).

‘header = 'col1 col2 col3' statement creates a string 'header' that will be used as the header for the text file.

‘np.savetxt('temp.txt', x, fmt="%d", header=header)’ statement saves the 2D NumPy array 'x' to a text file named 'temp.txt' using the integer format ("%d") for the elements, and adds the specified header to the file.

‘result = np.loadtxt('temp.txt')’ statement loads the contents of the 'temp.txt' file into a NumPy array named 'result'.

Finally print(result) prints the loaded 'result' array.

Pictorial Presentation:

NumPy: Save a given array to a text file and load it.

Python-Numpy Code Editor:

Previous: NumPy program to save two given arrays into a single file in compressed format (.npz format) and load it.
Next: NumPy program to convert a given array into bytes, and load it as array.

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.