Movatterモバイル変換


[0]ホーム

URL:


Python Tutorial

Python Array tofile() Method



The Python arraytofile() method is used to append all the elements of an array to the file.

Syntax

Following is the syntax of Python arraytofile() method −

array_name.tofile(f)

Parameters

This method accepts file object as a parameter.

Return Value

This method does not return any value.

Example 1

Following is the basic example of Python arraytofile() method.

Here, We have appended an array ofunicode charater to the filetofile.txt

import osimport array as arr#creating an arraymy_arr1=arr.array('u',['1','2','3','4','5'])print("Array Elements :", my_arr1)f=open('tofile.txt','wb')#Appending the array to the filemy_arr1.tofile(f)f.close#Reading the elements from filef=open("tofile.txt","r")data=f.read()print("File After appending array :",data)f.close

Output

Following is the output of the above code −

Array Elements : array('u', '12345')File After appending array : 1 2 3 4 5

Example 2

Lets try to append an array ofint data type to the filetofile.txt

import array as arr# Creating an arraymy_arr1 = arr.array('i', [10, 20, 30, 40, 50])print("Array Elements:", my_arr1)# Writing the array to a filef = open('tofile.txt', 'wb')my_arr1.tofile(f)f.close()# Reading the array back from the filef = open('tofile.txt', 'rb')my_arr2 = arr.array('i')my_arr2.fromfile(f, len(my_arr1))f.close()print("File After reading array:", my_arr2)

Output

Following is the output of the above code −

Array Elements: array('i', [10, 20, 30, 40, 50])File After Appending Array: array('i', [10, 20, 30, 40, 50])
python_array_methods.htm
Print Page
Advertisements

[8]ページ先頭

©2009-2025 Movatter.jp