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 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.

Return value

This function does not return any values.

Code example

#import modules
import os
from array import array
#open file object for writing
f = open('my_file.txt','wb')
#write array of integers to file object
array("i", [1, 2, 3, 4, 5, 6, 7, 8, 9]).tofile(f)
#close file
f.close()
#open file for reading
f = open('my_file.txt','rb')
#initialize array with integer type
array_one = array("i")
#initialize array with integer type
array_two = array("i")
#read 3 items from file
array_one.fromfile(f,3)
print(array_one)
#read 6 items from file
array_two.fromfile(f,6)
print(array_two)
#close file
f.close()

Code explanation

  • 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.

Free Resources