Python Array tofile() Method
The Python array tofile() method is used to append all the elements of an array to the file.
Syntax
Following is the syntax of Python array tofile() method −
array_name.tofile(f)
Parameters
This method accepts file object as a parameter.
Return Value
This method does not return any value.
Example 1
Following is the basic example of Python array tofile() method.
Here, We have appended an array of unicode charater to the file tofile.txt −
import os
import array as arr
#creating an array
my_arr1=arr.array('u',['1','2','3','4','5'])
print("Array Elements :", my_arr1)
f=open('tofile.txt','wb')
#Appending the array to the file
my_arr1.tofile(f)
f.close
#Reading the elements from file
f=open("tofile.txt","r")
data=f.read()
print("File After appending array :",data)
f.close
Output
Following is the output of the above code −
Array Elements : array('u', '12345')
File After appending array : 1 2 3 4 5
Example 2
Lets try to append an array of int data type to the file tofile.txt −
import array as arr
# Creating an array
my_arr1 = arr.array('i', [10, 20, 30, 40, 50])
print("Array Elements:", my_arr1)
# Writing the array to a file
f = open('tofile.txt', 'wb')
my_arr1.tofile(f)
f.close()
# Reading the array back from the file
f = open('tofile.txt', 'rb')
my_arr2 = arr.array('i')
my_arr2.fromfile(f, len(my_arr1))
f.close()
print("File After reading array:", my_arr2)
Output
Following is the output of the above code −
Array Elements: array('i', [10, 20, 30, 40, 50])
File After Appending Array: array('i', [10, 20, 30, 40, 50])
python_array_methods.htm