What is array.fromfile() 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.
One of these methods is the array.fromfile() method, which is used to append items for a file object to an array.
Syntax
array.fromfile(f, n)
Arguments
f: This is the file object from which items are to be appended to the array.n: This is the number of items fromfthat need to be appended to the array. Iffhas less thannitems,EOFErroris raised.
Both of the parameters listed above are necessary for the method to work.
Return value
This function does not return any values.
Code example
#import modulesimport osfrom array import array#open file object for writingf = open('my_file.txt','wb')#write array of integers to file objectarray("i", [1, 2, 3, 4, 5, 6, 7, 8, 9]).tofile(f)#close filef.close()#open file for readingf = open('my_file.txt','rb')#initialize array with integer typearray_one = array("i")#initialize array with integer typearray_two = array("i")#read 3 items from filearray_one.fromfile(f,3)print(array_one)#read 6 items from filearray_two.fromfile(f,6)print(array_two)#close filef.close()
Code explanation
-
Lines 2–3: We import the
osandarraymodule. -
Line 6: We open a new file for writing. We mention
wb, which means that we are writing in binary mode. -
Line 9: We append integers to the file object
ffrom the array, usingarray.tofile(f). -
Line 12: We close the file object
f. -
Line 15: We open the file object
ffor reading. -
Lines 18–21: We initialize the arrays with the
integertype. -
Lines 24–25: We append
3items from the file objectftoarray_one, usingarray.tromfile(). We print the array after appending the items to it. -
Line 28: We append
6items from the file objectftoarray_two, usingarray.tromfile(). We print the array after appending the items to it. -
Line 32: We close the file object
f.