Python Array tofile() 方法用于将数组的所有元素附加到文件中。
语法
以下是 Python Array tofile() 方法的语法 -
array_name.tofile(f)
参数
此方法接受 file object 作为参数。
返回值
此方法不返回任何值。
示例 1
以下是 Python Array tofile() 方法的基本示例。
在这里,我们在文件 tofile.txt 中附加了一个 unicode charater 数组 -
import os
import array as arr
#creating an array
my_arr1=arr.array('u',['1','2','3','4','5'])
print("Array Elements :", my_arr1)
f=open('tofile.txt','wb')
#Appending the array to the file
my_arr1.tofile(f)
f.close
#Reading the elements from file
f=open("tofile.txt","r")
data=f.read()
print("File After appending array :",data)
f.close
输出
以下是上述代码的输出 -
Array Elements : array('u', '12345')
File After appending array : 1 2 3 4 5
File After appending array : 1 2 3 4 5
示例 2
让我们尝试将 int 数据类型的数组附加到文件 tofile.txt -
import array as arr
# Creating an array
my_arr1 = arr.array('i', [10, 20, 30, 40, 50])
print("Array Elements:", my_arr1)
# Writing the array to a file
f = open('tofile.txt', 'wb')
my_arr1.tofile(f)
f.close()
# Reading the array back from the file
f = 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)
输出
以下是上述代码的输出 -
Array Elements: array('i', [10, 20, 30, 40, 50])
File After Appending Array: array('i', [10, 20, 30, 40, 50])
File After Appending Array: array('i', [10, 20, 30, 40, 50])