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.
array.fromfile(f, n)
f
: This is the file object from which items are to be appended to the array.n
: This is the number of items from f
that need to be appended to the array. If f
has less than n
items, EOFError
is raised.Both of the parameters listed above are necessary for the method to work.
This function does not return any values.
#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()
Lines 2–3: We import the os
and array
module.
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 f
from the array, using array.tofile(f)
.
Line 12: We close the file object f
.
Line 15: We open the file object f
for reading.
Lines 18–21: We initialize the arrays with the integer
type.
Lines 24–25: We append 3
items from the file object f
to array_one
, using array.tromfile()
. We print the array after appending the items to it.
Line 28: We append 6
items from the file object f
to array_two
, using array.tromfile()
. We print the array after appending the items to it.
Line 32: We close the file object f
.