Python Array - Write to File
Write Python Array to File
In Python, you can write the data in array to a file, using tofile() method of array instance.
In this tutorial, you will learn how to write a given Python array to a file, with examples.
To write a Python array to a file, open file in write binary mode, and pass the file object as argument to the tofile() method.
In the following code snippet, we write the array my_array to my_file.txt.
with open('my_file.txt', 'wb') as file:
my_array.tofile(file)
You may change the file name as per your requirement.
1. Write given Integer Array to a File
In the following program, we take an integer array my_array with some initial values, and then write the contents of this array to a file using tofile() method.
Python Program
import array as arr
my_array = arr.array('i', [10, 15, 20, 25, 30, 35])
with open('my_file.txt', 'wb') as file:
my_array.tofile(file)
Summary
In this Python Array tutorial, we learned how to write the contents of a given Python Array to a file, using tofile() method, with examples.