【发布时间】:2015-10-13 15:58:20
【问题描述】:
在 Nim 中写入和读取二进制文件的最佳方法是什么?我想将交替的浮点数和整数写入二进制文件,然后能够读取该文件。要在 Python 中编写这个二进制文件,我会做类似的事情
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)
在本例中,读取文件后,arr 将是
[(0.5, 1), (1.5, 2), (2.5, 3)]
在 Nim 中寻找类似的功能。
【问题讨论】:
标签: io binaryfiles nim-lang