Python Array fromfile() 方法用于将文件对象中的项目附加到数组中。
语法
以下是 Python Array fromfile() 方法的语法 -
参数
此方法接受以下参数 -
- f :这是要从中将项目附加到数组的文件对象。
- n :这是文件中需要附加到数组的项目数。
返回值
此方法不返回任何值。
示例 1
以下是 Python Array fromfile() 方法的基本示例 -
输出
以下是上述代码的输出 -
Array in the file : array('i', [1, 2, 3, 4, 5, 6, 7, 8, 9])
Appended array1 : array('i', [1, 2, 3])
Appended array2 : array('i', [1, 2, 3, 4, 5, 6])
Appended array1 : array('i', [1, 2, 3])
Appended array2 : array('i', [1, 2, 3, 4, 5, 6])
示例 2
让我们尝试将 unicode charater 数据类型的数组从一个文件附加到另一个数组 -
输出
Array elements in the file : array('u', 'abcd')
Array element after appending from file : array('u', 'abcd')
Array element after appending from file : array('u', 'abcd')
示例 3
在这种方法中,如果文件 f 的项目或元素的数量少于 n 个项目,我们会得到 EOF 错误。
此处,文件元素数为 5,提到的 n 值为 6
输出
Length of the array in the file 5
Array elements in the file : array('d', [5.6, 3.9, 23.5, 45.7, 12.7])
Traceback (most recent call last):
File "E:\pgms\Arraymethods prgs\fromfile1.py", line 63, in
arr4.fromfile(f1,6)
EOFError: read() didn't return enough bytes
Array elements in the file : array('d', [5.6, 3.9, 23.5, 45.7, 12.7])
Traceback (most recent call last):
File "E:\pgms\Arraymethods prgs\fromfile1.py", line 63, in
arr4.fromfile(f1,6)
EOFError: read() didn't return enough bytes