• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Save Numpy Array to Text File in Python

Save Numpy Array to Text File in Python

Author: Aditya Raj
Last Updated: August 8, 2022

Numpy arrays are used extensively while data analysis in python. In this article, we will discuss how we can save a numpy array to a text file in python.

Save Numpy Array to Text File Using the str() Function

We can save a numpy array to a text file using the str() function and file handling. In this approach, we will first convert the numpy array to a string using the str() function. The str() function takes the numpy array as the input argument and returns its string representation.  After converting the numpy array to a string, we will save the string to a text file.

To save the numpy array into a text file, we will first open a file in append mode using the open() function. The open() function takes the file name as its first input argument and the literal “a” as the second input argument to denote that the file is opened in the append mode. After execution, it returns a file object that contains the text file.

After getting the file object, we will use the write() method to save the string containing the numpy array to the file. The write() method, when invoked on a file object, takes the string as its input argument and appends the string to the file. After writing the string to the file, don’t forget to close the file using the close() method.

The complete code to save a numpy array to a text file using the str() function is as follows.

import numpy as np

myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
print("The content of the file before saving the array is:")
text = myFile.read()
print(text)
myFile.write(str(myArray))
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)

Output:

The array is: [1 2 3 4 5 6 7 8 9]
The content of the file before saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.

The content of the file after saving the array is:
I am a sample text file.
I was created by Aditya.
You are reading me at Pythonforbeginners.com.
[1 2 3 4 5 6 7 8 9]

Suggested Machine Learning Article: Regression in Machine Learning With Examples

Save Numpy Array to Text File using numpy.savetxt() function

Instead of using the str() function, we can use the numpy.savetxt() function to save a numpy array to a text file in python. In this approach, we first open the text file in the append mode using the open() function as discussed in the previous example. After opening the file, we will use the numpy.savetxt() function to save the array to the text file. Here, the numpy.savetxt() function takes the file object as its first input argument and the numpy array as its second input argument. After execution, it saves the numpy array to the text file. You can observe this in the following example.

import numpy as np

myFile = open('sample.txt', 'r+')
myArray = np.array([1, 2, 3, 4, 5, 6, 7, 8, 9])
print("The array is:", myArray)
np.savetxt(myFile, myArray)
myFile.close()
myFile = open('sample.txt', 'r')
print("The content of the file after saving the array is:")
text = myFile.read()
print(text)

Output:

The array is: [1 2 3 4 5 6 7 8 9]
The content of the file after saving the array is:
1.000000000000000000e+00
2.000000000000000000e+00
3.000000000000000000e+00
4.000000000000000000e+00
5.000000000000000000e+00
6.000000000000000000e+00
7.000000000000000000e+00
8.000000000000000000e+00
9.000000000000000000e+00

After, execution of the savetxt() function, you must close the file object using the close() object. Otherwise, the changes will not be written to the file.

Conclusion

In this article, we have discussed two approaches to save a numpy array to a text file in python. To know more about Python programming, you can read this article on list comprehension in Python. You might also like this article on dictionary comprehension in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us