Open In App

How to save a NumPy array to a text file?

Last Updated : 18 Jun, 2021
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Share
Report
News Follow

Let us see how to save a numpy array to a text file.

Method 1: Using File handling 
Creating a text file using the in-built open() function and then converting the array into string and writing it into the text file using the write() function. Finally closing the file using close() function. Below are some programs of the this approach: 

  • Example 1: 

Python3




# Program to save a NumPy array to a text file
 
# Importing required libraries
import numpy
 
# Creating an array
List = [1, 2, 3, 4, 5]
Array = numpy.array(List)
 
# Displaying the array
print('Array:\n', Array)
file = open("file1.txt", "w+")
 
# Saving the array in a text file
content = str(Array)
file.write(content)
file.close()
 
# Displaying the contents of the text file
file = open("file1.txt", "r")
content = file.read()
 
print("\nContent in file1.txt:\n", content)
file.close()


  • Output: 
Array:
 [1 2 3 4 5]

Content in file1.txt:
 [1 2 3 4 5]
  • Example 2: 

Python3




# Program to save a NumPy array to a text file
 
# Importing required libraries
import numpy
 
# Creating 2D array
List = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Array = numpy.array(List)
 
# Displaying the array
print('Array:\n', Array)
file = open("file2.txt", "w+")
 
# Saving the 2D array in a text file
content = str(Array)
file.write(content)
file.close()
 
# Displaying the contents of the text file
file = open("file2.txt", "r")
content = file.read()
 
print("\nContent in file2.txt:\n", content)
file.close()


  • Output: 
Array:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

Content in file2.txt:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]
  • Method 2:

Using NumPy functions

After creating the array, the 

numpy.savetxt()

function can be used to save the array into a text file. Below are some programs of this approach.

  • Example 1: 

Python3




# Program to save a NumPy array to a text file
 
# Importing required libraries
import numpy
 
# Creating an array
List = [1, 2, 3, 4, 5]
Array = numpy.array(List)
 
# Displaying the array
print('Array:\n', Array)
 
# Saving the array in a text file
numpy.savetxt("file1.txt", Array)
 
# Displaying the contents of the text file
content = numpy.loadtxt('file1.txt')
print("\nContent in file1.txt:\n", content)


  • Output: 
Array:
 [1 2 3 4 5]

Content in file1.txt:
 [1. 2. 3. 4. 5.]
  • Example 2: 

Python3




# Program to save a NumPy array to a text file
 
# Importing required libraries
import numpy
 
# Creating 2D array
List = [[1, 2, 3], [4, 5, 6], [7, 8, 9]]
Array = numpy.array(List)
 
# Displaying the array
print('Array:\n', Array)
 
# Saving the 2D array in a text file
numpy.savetxt("file2.txt", Array)
 
# Displaying the contents of the text file
content = numpy.loadtxt('file2.txt')
print("\nContent in file2.txt:\n", content)


  • Output: 
Array:
 [[1 2 3]
 [4 5 6]
 [7 8 9]]

Content in file2.txt:
 [[1. 2. 3.]
 [4. 5. 6.]
 [7. 8. 9.]]

 


Level up your coding with DSA Python in 90 days! Master key algorithms, solve complex problems, and prepare for top tech interviews. Join the Three 90 Challenge—complete 90% of the course in 90 days and earn a 90% refund. Start your Python DSA journey today!


Next Article
Practice Tags :

Similar Reads

NumPy save() Method | Save Array to a File
The NumPy save() method is used to store the input array in a binary file with the 'npy extension' (.npy). Example: Python3 import numpy as np a = np.arange(5) np.save('array_file', a) SyntaxSyntax: numpy.save(file, arr, allow_pickle=True, fix_imports=True) Parameters: file: File or filename to which the data is saved. If the file is a string or P
2 min read
How to extract paragraph from a website and save it as a text file?
Perquisites: Beautiful soupUrllib Scraping is an essential technique which helps us to retrieve useful data from a URL or a html file that can be used in another manner. The given article shows how to extract paragraph from a URL and save it as a text file. Modules Needed bs4: Beautiful Soup(bs4) is a Python library used for getting data from HTM
2 min read
Ways To Save Python Terminal Output To A Text File
Python provides various methods for redirecting and saving the output generated in the terminal to a text file. This functionality can be useful for logging, debugging, or simply capturing the results of a script. In this article, we'll explore different ways to save Python terminal output to a text file. Save Python Terminal Output to a Text File
2 min read
How to save file with file name from user using Python?
Prerequisites: File Handling in PythonReading and Writing to text files in Python Saving a file with the user's custom name can be achieved using python file handling concepts. Python provides inbuilt functions for working with files. The file can be saved with the user preferred name by creating a new file, renaming the existing file, making a cop
5 min read
Save Plot To Numpy Array using Matplotlib
Saving a plot to a NumPy array in Python is a technique that bridges data visualization with array manipulation allowing for the direct storage of graphical plots as array representations, facilitating further computational analyses or modifications within a Python environment. Let's learn how to Save Plot to NumPy Array using Matplotlib. How to Sa
4 min read
How To Save Multiple Numpy Arrays
NumPy is a powerful Python framework for numerical computing that supports massive, multi-dimensional arrays and matrices and offers a number of mathematical functions for modifying the arrays. It is an essential store for Python activities involving scientific computing, data analysis, and machine learning. What is a Numpy array?A NumPy array is a
3 min read
Save a dictionary to a file
A dictionary in Python is a collection where every value is mapped to a key. They are unordered, mutable and there is no constraint on the data type of values and keys stored in the dictionary. This makes it tricky for dictionaries to be stored as files. Know more about dictionaries here. Syntax: dictionary = {'geek': 1, 'supergeek': True, 4: 'geek
2 min read
How to Save Pandas Dataframe as gzip/zip File?
Pandas is an open-source library that is built on top of NumPy library. It is a Python package that offers various data structures and operations for manipulating numerical data and time series. It is mainly popular for importing and analyzing data much easier. Pandas is fast and it has high-performance & productivity for users. Converting to
2 min read
How to Save a Plot to a File Using Matplotlib?
Matplotlib is a widely used Python library to plot graphs, plots, charts, etc. show() method is used to display graphs as output, but don’t save it in any file. In this article, we will see how to save a Matplotlib plot as an image file. Save a plot in MatplotlibBelow are the ways by which we can save a plot to a file using Matplotlib in Python: Us
3 min read
Python PIL save file with datetime as name
In this article, we are going to see how to save image files with datetime as a name using PIL Python. Modules required: PIL: This library provides extensive file format support, an efficient internal representation, and fairly powerful image processing capabilities. pip install Pillow datetime: This module helps us to work with dates and times in
2 min read
  翻译: