How to Write a NumPy Array to a Text File

5/5 - (1 vote)

Problem Formulation and Solution Overview

In this article, you’ll learn how to write a 1D, 2D and 3D NumPy Array to a file in Python.

To make it more fun, we have the following running scenario:

Bart, a Manager at ShopSmart (and part-time Python coder), is responsible for purchasing Lottery Numbers for their group. Bart needs help writing a script that generates random numbers and writes them to a flat-text file using functions from the NumPy library.

πŸ’¬ Question: How would we write code to write this data to a flat-text file?

We can accomplish this task by one of the following options:


Preparation

Before moving forward, please ensure the NumPy library is installed on the computer. Click here if you require instructions.

Add the following code to the top of each script. This snippet will allow the code in this article to run error-free.

import numpy as np 
import random

In this article, the random library is imported to generate arbitrary integers for Lottery numbers.


Method 1: Use savetxt() to write a 1D NumPy Array

A simple way to write a NumPy 1D array to a flat-text file is by using the savetxt() function and passing the appropriate arguments.

import random

lotto_649 = np.array(np.random.randint(1, 100, 7))
np.savetxt('lotto_649.txt', lotto_649, newline=' ', fmt="%d")

Above, a NumPy array (np.array()) is called and passed the random integer generator (random.rand.int()). This function is then passed three (3) arguments: (start, stop, length). Then, the seven (7) random Lottery numbers save to lotto_649.

Next, np.savetxt() is called and passed the following four (4) arguments:

  1. The filename, lotto_649.txt.
  2. The NumPy array, lotto_649.
  3. The optional newline character. By default, a newline (\n) is appended to the end of each element. This changes to writing each element on a single line, separated by spaces (newline=' ').
  4. The integer format. By default, floats are displayed. Modifying the format option to fmt="%d" changes the display to integers.

If successful, the abovementioned file resides in the current working directory containing seven (7) random integers on a single line.

File Contents

52 77 20 64 82 17 83
NumPy Tutorial - Everything You Need to Know to Get Started

Method 2: Use open(), map() and join() to write a 1D NumPy Array

Another way to write a NumPy 1D array to a flat-text file is by using open() and writing the contents using map() and join().

lotto_max = np.array(np.random.randint(1, 100, 8))

with open('lotto_max.txt', 'w') as fp:
    fp.write(','.join(map(str, lotto_max)))

Above, a NumPy array (np.array()) is called and passed the random integer generator (random.rand.int()). This function is then passed three (3) arguments: (start, stop, length). Then, the eight (8) random Lottery numbers save to lotto_max.

Next, open() is called to open the specified file (lotto_max.txt) in write (w) mode and create a File Object (fp).

πŸ’‘Note: The File Object allows access to and manipulation of a file.

Once open, the following occurs:

  • The map() function is called. This function takes two (2) arguments: a function (str) and an iterable (lotto_max). This returns an iterable map() object, similar to below:
    <map object at 0x0000021DCABF62C0>
  • Then, the join() function is called. This function iterates through the returned map() object, joins each element with a comma (‘,’), and writes to the file.

If successful, the abovementioned file resides in the current working directory containing eight (8) random integers on a single line.

File Contents

22, 8, 9, 93, 6, 10, 8, 42
Python open() Function – An 80/20 Guide by Example

Method 3: Use savetxt() and reshape() to Write a 1D NumPy Array

To write a NumPy 1D array to a flat-text file with a different display, use savetxt() and reshape().

For this example, Bart has generated two (2) Pick5 lottery tickets, which are saved to a NumPy 1D array. Let’s use reshape() to resolve the issue.

pick_five = np.array([52, 77, 20, 64, 82, 17, 83, 22, 8, 42]).reshape(2,5)
np.savetxt('pick_five.txt', pick_five, fmt='%d')

Above, a NumPy 1D array is created with 10 tickets numbers. However, each ticket should contain five (5) numbers. The reshape() function modifies the original array into two (2) rows, five (5) elements per row. The results save to pick_five.

Next, savetxt() is called and the following three (3) arguments are passed:

  1. The filename, both_lottos.txt.
  2. The NumPy array, pick_five.txt.
  3. The integer format. By default, floats are displayed. Modifying the format option to fmt="%d" changes the display to integers.

If successful, the abovementioned file resides in the current working directory.

File Contents

52 77 20 64 82
9 17 5 11 13

Method 4: Use savetxt() to write a 2D NumPy Array

To write a NumPy 2D array to a flat-text file with a row-wise display, use savetxt().

two_lottos = np.array([[15, 37, 43, 49, 11], [4, 18, 36, 12, 22]])
np.savetxt('two_lottos.txt', two_lottos, fmt='%d')

Above creates a 2D NumPy array; each dimension contains five (5) numbers. The results save to two_lottos.

Next, savetxt() is called and the following three (3) arguments are passed:

  1. The filename, two_lottos.txt.
  2. The NumPy array, two_lottos.
  3. The integer format. By default, floats are displayed. Modifying the format option to fmt="%d" changes the display to integers.

If successful, the abovementioned file resides in the current working directory.

File Contents

15 37 43 49 11
4 18 36 12 22

Method 5: Use save() to write a 3D NumPy Array

Unfortunately, flat-text files are not able to handle 3D NumPy arrays. Therefore, savetxt() used in the above examples will not work here and, in fact, generate an error. The save() function will need to be used.

big3_lotto = np.array([[[15, 37, 43, 54], [3, 18, 36, 12]]])
np.save('big3_lotto', big3_lotto)

Above, creates a 3D NumPy array. The results save to big3_lotto.

Next, save() is called and the following two (2) arguments are passed:

  1. The filename, big3_lotto. Do not add an extension here as a Binary file with the extension of .npy will be created (big3_lotto.npy).
  2. The NumPy array, big3_lotto.

If successful, the abovementioned file resides in the current working directory.

To view the file contents, run the following code.

results = np.load('big3_lotto.npy', allow_pickle=True)
print(results)

To read in the Binary file, np.load() is called and the following arguments are passed:

  1. The filename, big3_lotto.npy.
  2. The allow_pickle argument set to True.

πŸ’‘Note: The argument, allow_pickle=True, allows loading pickled object array stored in an .npy file. 

File Contents

[[[15 37 43 54]
[ 3 18 36 12]]]

Summary

These methods of writing a NumPy array to a flat-text file should give you enough information to select the best one for your coding requirements.

Good Luck & Happy Coding!


Programmer Humor

It’s hard to train deep learning algorithms when most of the positive feedback they get is sarcastic. — from xkcd