Trusted answers to developer questions
Trusted Answers to Developer Questions

Related Tags

array
python
communitycreator
tofile

What is array.tofile() in Python?

Eman Kashif

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 modules
import os
from array import array

#initialize array with unicode characters
array_one = array("u", ['a','b','c','d'])

#initialize array with unicode characters
array_two = array("u", ['e','f','g'])

#open file object for writing
f = open('my_file.txt','wb')

print (array_one)
#append array to file object
array_one.tofile(f)
print ("\n")

print (array_two)
#append array to file object
array_two.tofile(f)

#close file object
f.close()
print ("\n")

#open file object for reading
f = open('my_file.txt','r')

#read file object
text = f.read()

#print contents of file object
print(text)

#close file object
f.close()

Explanation

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

RELATED TAGS

array
python
communitycreator
tofile
RELATED COURSES

View all Courses

Keep Exploring