Python write int array to file

I have 3000000 ints' long array which I want to output to a file. How can I do that? Also, is this

for i in range(1000):
    for k in range(1000):
        (r, g, b) = rgb_im.getpixel((i, k))
        rr.append(r)
        gg.append(g)
        bb.append(b)
d.extend(rr)
d.extend(gg)
d.extend(bb)

a good practice to join array together?

All of the arrays are declared like this d = array('B')

EDIT: Managed to output all int`s delimited by ' ' with this

from PIL import Image
import array

side = 500

for j in range(1000):
    im = Image.open(r'C:\Users\Ivars\Desktop\RS\Shape\%02d.jpg' % (j))
    rgb_im = im.convert('RGB')
    d = array.array('B')
    rr = array.array('B')
    gg = array.array('B')
    bb = array.array('B')
    f = open(r'C:\Users\Ivars\Desktop\RS\ShapeData\%02d.txt' % (j), 'w')
    for i in range(side):
        for k in range(side):
            (r, g, b) = rgb_im.getpixel((i, k))
            rr.append(r)
            gg.append(g)
            bb.append(b)
    d.extend(rr)
    d.extend(gg)
    d.extend(bb)
    o = ' '.join(str(t) for t in d)
    print('#', j, ' - ', len(o))
    f.write(o)
    f.close()

  1. HowTo
  2. Python How-To's
  3. Write an Array to a Text File in Python

Created: December-20, 2021 | Updated: April-14, 2022

  1. Write an Array to Text File Using open() and close() Functions in Python
  2. Write an Array to Text File Using Content Manager in Python

Reading and writing files is an important aspect of building programs used by many users. Python offers a range of methods that can be used for resource handling. These methods may be slightly different depending on the format of the file and the operation being performed.

Besides the traditional way of creating files by clicking buttons, we can also create files using built-in functions such as the open() function. Please note that the open() function will only create a file if it does not exist; otherwise, it’s intrinsically used to open files.

Write an Array to Text File Using open() and close() Functions in Python

Since the open() function is not used in seclusion, combining it with other functions, we can perform even more file operations such as writing and modifying or overwriting files.These functions include the write() and close() functions. Using these functions, we will create an array using NumPy and write it to a text file using the write function as shown in the program below.

import numpy as np

sample_list = [23, 22, 24, 25]
new_array = np.array(sample_list)

# Displaying the array

file = open("sample.txt", "w+")

# Saving the array in a text file
content = str(new_array)
file.write(content)
file.close()

# Displaying the contents of the text file
file = open("sample.txt", "r")
content = file.read()

print("Array contents in sample.txt: ", content)
file.close()

Output:

Array contents in text_sample.txt:  [23 22 24 25]

We have created a text file named sample.txt using the open function in write mode in the example above. We have then proceeded to convert the array into string format before writing its contents to the text file using the write function. Using the open() functions, we opened the contents of the text file in reading mode. The text file contents are displayed in the terminal and can also be viewed by physically opening the text file.

Similarly, we can also create a multi-dimensional array and save it to a text file, as shown below.

import numpy as np

sample_list = [[23, 22, 24, 25], [13, 14, 15, 19]]
new_array = np.array(sample_list)

# Displaying the array

file = open("sample.txt", "w+")

# Saving the array in a text file
content = str(new_array)
file.write(content)
file.close()

# Displaying the contents of the text file
file = open("sample.txt", "r")
content = file.read()

print("Array contents in sample.txt: ", content)
file.close()

Output:

Array contents in sample.txt:  [[23 22 24 25]
[13 14 15 19]]

Write an Array to Text File Using Content Manager in Python

Alternatively, we can use the context manager to write an array to a text file. Unlike the open() function, where we have to close the files once we have opened them using the close() function, the content manager allows us to open and close files precisely when we need them. In Python, using the context manager is considered a better practice when managing resources instead of using the open() and close() functions. The context manager can be implemented using the with keyword shown below.

import numpy as np

new_list = [23, 25, 27, 29, 30]
new_array = np.array(new_list)
print(new_array)

with open("sample.txt", "w+") as f:
  data = f.read()
  f.write(str(new_array))

Output:

[23 25 27 29 30]

In the example above, the context manager opens the text file sample.txt, and since the file does not exist, the context manager creates it. Within the scope of the context manager, we have written the array to the text file upon converting it into a string. Once we opt out of the indentation, the context manager closes the file automatically. Similarly, as shown below, we can also write multi-dimensional arrays to a text file using the context manager.

import numpy as np

new_list = [[23, 25, 27, 29],[30, 31, 32, 34]]
new_array = np.array(new_list)
print(new_array)

with open("sample.txt", "w+") as f:
  data = f.read()
  f.write(str(new_array))

Output:

[[23 25 27 29]
[30 31 32 34]]

NumPy is a scientific library that offers a range of functions for working with arrays. We can save an array to a text file using the numpy.savetxt() function. The function accepts several parameters, including the name of the file, the format, encoding format, delimiters separating the columns, the header, the footer, and comments accompanying the file.

In addition to this the NumPy function also offers the numpy.loadtxt() function to load a text file.

We can save an array to a text file and load it using these two functions, as shown in the code below.

import numpy as np

new_list = [23, 24, 25, 26, 28]
new_array = np.array(new_list)
print(new_array)

np.savetxt("sample.txt", new_array, delimiter =", ")

content = np.loadtxt("sample.txt")
print(content)

Output:

[23 24 25 26 28]

As shown below, we can also use these functions to save multi-dimensional arrays to a text file.

import numpy as np

new_list = [[23, 24, 25, 26, 28],[34, 45, 46, 49, 48]]
new_array = np.array(new_list)
print(new_array)

np.savetxt("sample7.txt", new_array, delimiter =", ")

content = np.loadtxt("sample7.txt")
print(content)

Output:

[[23 24 25 26 28]
 [34 45 46 49 48]]

Related Article - Python Array

  • Initiate 2-D Array in Python
  • Count the Occurrences of an Item in a One-Dimensional Array in Python
  • Sort 2D Array in Python
  • Create a BitArray in Python
  • Python write int array to file

    How do you write an array to a text file in Python?

    Use numpy..
    print(an_array).
    a_file = open("test.txt", "w").
    for row in an_array:.
    np. savetxt(a_file, row).
    a_file. close() close `a_file`.

    How do I save an array to a file?

    You can save your NumPy arrays to CSV files using the savetxt() function. This function takes a filename and array as arguments and saves the array into CSV format. You must also specify the delimiter; this is the character used to separate each variable in the file, most commonly a comma.

    How do I convert a NumPy array to a text file?

    Let us see how to save a numpy array to a text file. 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.

    How do you write a list of numbers in a file in Python?

    A common approach to write the elements of a list to a file using Python is to first loop through the elements of the list using a for loop. Then use a file object to write every element of the list to a file as part of each loop iteration. The file object needs to be opened in write mode.