What is array.tofile() in Python?
Overview
Python is a high-level programming language that provides functionalities for several operations. The array module comes with various methods to manipulate array data structures.
The function array.tofile() converts an array to a file object.
Syntax
array.tofile(f)
Parameters
f: This is the file object in which the items of the array are to be appended. This parameter is required.
Return value
This function does not return anything.
Example
#import modulesimport osfrom array import array#initialize array with unicode charactersarray_one = array("u", ['a','b','c','d'])#initialize array with unicode charactersarray_two = array("u", ['e','f','g'])#open file object for writingf = open('my_file.txt','wb')print (array_one)#append array to file objectarray_one.tofile(f)print ("\n")print (array_two)#append array to file objectarray_two.tofile(f)#close file objectf.close()print ("\n")#open file object for readingf = open('my_file.txt','r')#read file objecttext = f.read()#print contents of file objectprint(text)#close file objectf.close()
Explanation
-
Line 2: We import the
osmodule. -
Line 3: We import the
arraymodule. -
Lines 6 to 9: We initialize arrays with unicode characters.
-
Line 12: We open file object
ffor writing. -
Line 16 to 21: We append array to file object
fusing thearray.tofile(). -
Line 24: We close the file object
f. -
Line 28: We open the file object
ffor reading. -
Line 31: We read from the file object
f.