上面代码基础上,将bin文件按1、2、3的顺序分别放到csv的1、2、3列
时间: 2023-08-31 09:59:08 浏览: 40
以下是将 bin 文件按照顺序分别放入 csv 文件的不同列的示例程序:
```python
import os
import csv
import struct
def convert_bytes_to_float(bytes_data):
float_value = struct.unpack('d', bytes_data)[0]
return float_value
def convert_bin_to_csv(bin_file_path):
csv_file_path = os.path.splitext(bin_file_path)[0] + '.csv'
with open(bin_file_path, 'rb') as bin_file, open(csv_file_path, 'w', newline='') as csv_file:
bin_data = bin_file.read()
csv_writer = csv.writer(csv_file)
for i in range(0, len(bin_data), 24):
bytes_data1 = bin_data[i:i+8]
bytes_data2 = bin_data[i+8:i+16]
bytes_data3 = bin_data[i+16:i+24]
float_value1 = convert_bytes_to_float(bytes_data1)
float_value2 = convert_bytes_to_float(bytes_data2)
float_value3 = convert_bytes_to_float(bytes_data3)
csv_writer.writerow([float_value1, float_value2, float_value3])
# 指定要转换的 bin 文件路径
bin_file_path = 'path/to/your/file.bin'
convert_bin_to_csv(bin_file_path)
```
在上述代码中,我们假设 bin 文件中的每 24 个字节分别代表三个浮点数。我们按顺序将每个浮点数分别存储在 csv 文件的不同列中。
程序中,我们首先构造了 csv 文件的路径,通过使用 `os.path.splitext()` 函数将 bin 文件的后缀名替换为 ".csv"。然后,我们打开 bin 文件和 csv 文件,并读取 bin 文件内容。
在循环中,我们按照顺序提取每个浮点数的字节数据,并使用 `convert_bytes_to_float()` 函数将字节数据转换为浮点数。然后,我们将这三个浮点数按顺序写入 csv 文件的一行中。
请确保你已经安装了 Python,并且导入了 os、csv 和 struct 模块。将代码中的 `'path/to/your/file.bin'` 替换为你要转换的 bin 文件的路径。