10
在Nim中編寫和讀取二進制文件的最佳方式是什麼?我想寫一個二進制文件交替浮動和整數,然後能夠讀取文件。爲了寫這個二進制文件在Python我會做類似在Nim中寫入/讀取二進制文件
import struct
# list of alternating floats and ints
arr = [0.5, 1, 1.5, 2, 2.5, 3]
# here 'f' is for float and 'i' is for int
binStruct = struct.Struct('fi' * (len(arr)/2))
# put it into string format
packed = binStruct.pack(*tuple(arr))
# open file for writing in binary mode
with open('/path/to/my/file', 'wb') as fh:
fh.write(packed)
讀書,我會做類似
arr = []
with open('/path/to/my/file', 'rb') as fh:
data = fh.read()
for i in range(0, len(data), 8):
tup = binStruct.unpack('fi', data[i: i + 8])
arr.append(tup)
在這個例子中,讀取文件後,編曲將
[(0.5, 1), (1.5, 2), (2.5, 3)]
在Nim中尋找類似的功能。
這很好。 – COM