Problem Formulation and Solution Overview
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:
- The filename,
lotto_649.txt
. - The NumPy array,
lotto_649
. - The optional
newline
character. By default, anewline
(\n
) is appended to the end of each element. This changes to writing each element on a single line, separated by spaces (newline=' '
). - 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 |
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 iterablemap()
object, similar to below:
<map object at 0x0000021DCABF62C0> - Then, the
join()
function is called. This function iterates through the returnedmap()
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 |
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:
- The filename,
both_lottos.txt
. - The NumPy array,
pick_five.txt
. - 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 |
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:
- The filename,
two_lottos.txt
. - The NumPy array,
.two_lottos
- 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 |
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,
is called and the following two (2) arguments are passed:save()
- 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
). - 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:
- The filename,
big3_lotto.npy
. - 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] |