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.
array.tofile(f)
f
: This is the file object in which the items of the array are to be appended. This parameter is required.This function does not return anything.
#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()
Line 2: We import the os
module.
Line 3: We import the array
module.
Lines 6 to 9: We initialize arrays with unicode characters.
Line 12: We open file object f
for writing.
Line 16 to 21: We append array to file object f
using the array.tofile()
.
Line 24: We close the file object f
.
Line 28: We open the file object f
for reading.
Line 31: We read from the file object f
.