arrays - 循环一个字节数组以将 64 位转换为十进制
问题描述
我有一个非常大的文件,其中填充了 8 字节双精度数据。
我创建了这个循环来将所有数据转换为十进制,但我不断收到 TypeError: 'bytearray' object cannot be mapped as an integer
有小费吗?
import numpy as np
import matplotlib.pyplot as plt
import struct
#import file
f=open('nohead.stk','rb')
#Read in the data as a byte array (8-bit array)
ba = bytearray(f.read())
#number of bytes in the data file
length = len(ba)
print('N-bytes=',length)
#Since the data is in 64bits, convert eight bits at a time to a 64 bit
#Number of data points in file
nvals = int(length/8);
print('N-recordings for 64bits (8-byte data)=',nvals)
#loop over all values
for i in range(nvals):
eightbytes[i] = ba[(i*8):(8+i*8)]
unpacked[i] = struct.unpack('<d', eightbytes[i])[0]
f= open("Reading_Decimal.csv","w+")
f.write("%f\n" % (unpacked[i]))
f.close();
我在此处附加了前 24 个字节,因此您可以将其保存到文件中,看看是否可以让循环在前 3 个小数上工作
应该在-6左右
字节数组(b'\xef,\x81\xb6\\xf1\x17\xc0\xff\xe0\x9b\x80\xb6\xeb\x17\xc0\xbd\x98V\xb0\xbd\xa3\x17\xc0')
干杯
解决方案
自己得到了答案
希望这可以帮助其他人
import numpy as np
import matplotlib.pyplot as plt
import struct
#import file with no headers
f=open('15_stack_noheaders.stk','rb')
#Read in the data as a byte array (8-bit array)
ba = bytearray(f.read())
bs=str(ba)
#number of bytes in the data file
length = len(ba)
print('N-bytes=',length)
#Since the data is in 64bits, convert eight bits at a time to a 64 bit
#Number of data points in file
nvals = int(length/8);
print('N-recordings for 64bits (8-byte data)=',nvals)
#create empty array of zeros to fill
dat = np.zeros(nvals)
for i in range(0,nvals):
dat[i] = struct.unpack('<d',ba[8*i:8+i*8])[0]
f= open("output.csv","w+")
for i in range(nvals) :
f.write("%f\n" % (dat[i]))
f.close();
推荐阅读
- sqlite - 字符串与整数
- c - C、FLT_MAX值大于32位?
- apache - 暂停服务。Apache2 centos 7
- dart - 画布drawImage方法不绘制
- arrays - 比较两个数组并删除相同的值
- arrays - Run specific macro if ActiveSheet.Name is listed in an array
- javascript - highcharts.js - 动态标签颜色
- wordpress - wordpress custom type active menu in header
- python - 获取没有类似 JSON 样式的 mysql python 的列表
- android - cr_VariationsUtils: Failed reading seed file