我想从txt文件编写和读取Python数组。我知道如何编写它,但是读取数组需要我提供有关数组长度的参数。我没有提前数组的长度,有没有一种方法可以读取数组而不计算其长度。我的工作代码如下。如果我在a.fromfile中提供2作为第二个参数,它将读取数组的第一个元素,我希望读取所有元素(基本上是要重新创建的数组)。
from __future__ import division
from array import array
L = [1,2,3,4]
indexes = array('I', L)
with open('indexes.txt', 'w') as fileW:
indexes.tofile(fileW)
a = array('I', [])
with open('indexes.txt', 'r') as fileR:
a.fromfile(fileR,1)
Run Code Online (Sandbox Code Playgroud)
我不知道为什么.fromfile要您指定一些对象,但.frombytes没有。您可以只从文件中读取字节并将其附加到数组。
这适用于python3:
with open('indexes.txt', 'rb') as fileR:
a.frombytes(fileR.read())
print(a)
Run Code Online (Sandbox Code Playgroud)
印刷品:
array('I', [1, 2, 3, 4])
Run Code Online (Sandbox Code Playgroud)
在python2中没有,.frombytes但.fromstring因为str它等效于python3 bytes:
with open('indexes.txt', 'rb') as fileR:
a.fromstring(fileR.read())
Run Code Online (Sandbox Code Playgroud)