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
Save
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.]]

 



Next Article

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: C/C++ Code 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
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 HTML
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
How To Save The Network In XML File Using PyBrain
In this article, we are going to see how to save the network in an XML file using PyBrain in Python. A network consists of several modules. These modules are generally connected with connections. PyBrain provides programmers with the support of neural networks. A network can be interpreted as an acyclic directed graph where each module serves the p
2 min read
Scrape and Save Table Data in CSV file using Selenium in Python
Selenium WebDriver is an open-source API that allows you to interact with a browser in the same way a real user would and its scripts are written in various languages i.e. Python, Java, C#, etc. Here we will be working with python to scrape data from tables on the web and store it as a CSV file. As Google Chrome is the most popular browser, to make
3 min read
Save multiple matplotlib figures in single PDF file using Python
In this article, we will discuss how to save multiple matplotlib figures in a single PDF file using Python. We can use the PdfPages class's savefig() method to save multiple plots in a single pdf. Matplotlib plots can simply be saved as PDF files with the .pdf extension. This saves Matplotlib-generated figures in a single PDF file named Save multip
3 min read
How to save a Python Dictionary to a CSV File?
Prerequisites: Working with csv files in Python CSV (comma-separated values) files are one of the easiest ways to transfer data in form of string especially to any spreadsheet program like Microsoft Excel or Google spreadsheet. In this article, we will see how to save a PYthon dictionary to a CSV file. Follow the below steps for the same. Import cs
2 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 z
2 min read
How to save pyttsx3 results to MP3 or WAV file?
In this article, we will see how to generate and save pyttsx3 results as mp3 and wav file. Pyttsx3 is a python module that provides a Text to Speech API. We can use this API to convert the text into voice. Environment setup: To use pyttsx3 we have to install espeak and ffmpeg first. sudo apt update sudo apt install espeak sudo apt install ffmpeg Ad
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
How to Save Seaborn Plot to a File in Python?
Seaborn provides a way to store the final output in different desired file formats like .png, .pdf, .tiff, .eps, etc. Let us see how to save the output graph to a specific file format. Saving a Seaborn Plot to a File in Python Import the inbuilt penguins dataset from seaborn package using the inbuilt function load_dataset. C/C++ Code # Import the s
2 min read
Save a image file on a Postgres database - Python
In this article, we are going to see how to save image files on a postgresql database using Python. Psycopg2 is a driver, that is used, for interacting, with Postgres data, using the Python scripting language. It is, used to perform, CRUD operations on Postgres data. Data handled in applications can be in any format. For example, Strings, Numbers,
4 min read
Save user input to a Excel File in Python
In this article, we will learn how to store user input in an excel sheet using Python, What is Excel? Excel is a spreadsheet in a computer application that is designed to add, display, analyze, organize, and manipulate data arranged in rows and columns. It is the most popular application for accounting, analytics, data presentation, etc. Methods us
4 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
Save Image To File in Python using Tkinter
Saving an uploaded image to a local directory using Tkinter combines the graphical user interface capabilities of Tkinter with the functionality of handling and storing images in Python. In this article, we will explore the steps involved in achieving this task, leveraging Tkinter's GUI features to enhance the user experience in image management ap
4 min read
Django - How to Create a File and Save It to a Model's FileField?
Django is a very powerful web framework; the biggest part of its simplification for building web applications is its built-in feature of handling file uploads with FileField. Images, documents, or any other file types, Django's FileField makes uploading files through our models easy. In this article, we will learn how to create a file and save it i
5 min read
NumPy Array Sorting | How to sort NumPy Array
Sorting an array is a very important step in data analysis as it helps in ordering data, and makes it easier to search and clean. In this tutorial, we will learn how to sort an array in NumPy. You can sort an array in NumPy: Using np.sort() functionin-line sortsorting along different axesUsing np.argsort() functionUsing np.lexsort() functionUsing s
4 min read
Convert Text and Text File to PDF using Python
PDFs are one of the most important and widely used digital media. PDF stands for Portable Document Format. It uses .pdf extension. It is used to present and exchange documents reliably, independent of software, hardware, or operating system. Converting a given text or a text file to PDF (Portable Document Format) is one of the basic requirements in
3 min read
Difference between Numpy array and Numpy matrix
While working with Python many times we come across the question that what exactly is the difference between a numpy array and numpy matrix, in this article we are going to read about the same. What is np.array() in PythonThe Numpy array object in Numpy is called ndarray. We can create ndarray using numpy.array() function. It is used to convert a l
3 min read
NumPy ndarray.tolist() Method | Convert NumPy Array to List
The ndarray.tolist() method converts a NumPy array into a nested Python list. It returns the array as an a.ndim-levels deep nested list of Python scalars. Data items are converted to the nearest compatible built-in Python type. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) print(gfg.tolist()) Output[1, 2, 3, 4, 5] SyntaxSynt
1 min read
NumPy ndarray.size() Method | Get Number of Elements in NumPy Array
The ndarray.size() method returns the number of elements in the NumPy array. It works the same as np.prod(a.shape), i.e., the product of the dimensions of the array. Example C/C++ Code import numpy as np arr = np.zeros((3, 4, 2), dtype = np.complex128) gfg = arr.size print (gfg) Output : 24Syntax Syntax: numpy.ndarray.size(arr) Parameters arr : [ar
1 min read
NumPy ndarray.__abs__() | Find Absolute Value of Elements in NumPy Array
The ndarray.__abs__() method returns the absolute value of every element in the NumPy array. It is automatically invoked when we use Python's built-in method abs() on a NumPy array. Example C/C++ Code import numpy as np gfg = np.array([1.45, 2.32, 3.98, 4.41, 5.55, 6.12]) print(gfg.__abs__()) Output[ 1 2 3 4 5 6] SyntaxSyntax: ndarray.__abs__() Ret
1 min read
NumPy ndarray.__ilshift__() | Shift NumPy Array Elements to Left
The ndarray.__ilshift__() method is an in-place left-shift operation. It shifts elements in the array to the left of the number of positions specified. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__ilshift__() method print(gfg.__ilshift__(2)) Output[ 4 8 12 16 20] SyntaxSyntax: ndarray.__ilshift__($self,
1 min read
NumPy ndarray.__irshift__() | Shift NumPy Array Elements to Right
The ndarray.__irshift__() method returns a new array where each element is right-shifted by the value that is passed as a parameter. Example C/C++ Code import numpy as np gfg = np.array([1, 2, 3, 4, 5]) # applying ndarray.__irshift__() method print(gfg.__irshift__(2)) Output[0 0 0 1 1] SyntaxSyntax: ndarray.__irshift__($self, value, /) Parameter se
1 min read
NumPy ndarray.imag() Method | Get Imaginary Part in NumPy Array
The ndarray.imag() method returns the imaginary part of the complex number in the NumPy array. Note: Remember resulting data type for the imaginary value is 'float64'. Example C/C++ Code # import the important module in python import numpy as np # make an array with numpy gfg = np.array([1 + 2j, 2 + 3j]) # applying ndarray.imag() method geeks = np.
1 min read
NumPy ndarray.transpose() Method | Find Transpose of the NumPy Array
The ndarray.transpose() function returns a view of the array with axes transposed. For a 1-D array, this has no effect, as a transposed vector is simply the same vector.For a 2-D array, this is a standard matrix transpose.For an n-D array, if axes are given, their order indicates how the axes are permuted. If axes are not provided and arr.shape = (
2 min read
How to Convert an image to NumPy array and saveit to CSV file using Python?
Let's see how to Convert an image to NumPy array and then save that array into CSV file in Python? First, we will learn about how to convert an image to a numpy ndarray. There are many methods to convert an image to ndarray, few of them are: Method 1: Using PIL and NumPy library. We will use PIL.Image.open() and numpy.asarray(). Example: C/C++ Code
4 min read
Practice Tags :
  翻译: