【问题标题】:Expecting delimiter in .bin file.bin 文件中需要分隔符
【发布时间】:2022-11-02 05:28:03
【问题描述】:

我目前正在处理由示波器软件生成的几个 .bin 文件。这些 .bin 文件由屏幕上的标题和 1.5k 点组成。我编写的用于处理这些 .bin 文件的程序的一部分提取标题并将其转换为 JSON 格式。使用此 .bin 文件 https://dropmefiles.com/6C2qr 我的程序运行良好,但是使用此文件 https://dropmefiles.com/ocM9H 程序返回此消息:

期望 ',' 分隔符:第 1 行第 820 列(字符 819)

我尝试使用hexdump 命令查看两个垃圾箱,但没有发现任何区别。可能是什么问题,我应该如何纠正它? 我用于提取 JSON 的代码(Python):

def HeaderToJSON(file):
    start = file.read(10) 
    print(start)
            
    chID = bytes()
    count = 0
    while True:       
        s = file.read(1)
        chID += s
        if s == b'}':
            count += 1
            if count == 6:
                break
    
    noise2 = f.read(4)

源代码:https://pastebin.com/938HDe40

【问题讨论】:

标签: python file io


【解决方案1】:

我查看了数据,我认为有一种更有效的方法可以做到这一点,而且不会出错。

前 6 个字节似乎是某种前导码。接下来的四个字节显示为 JSON 标头信息的长度。这允许提取 JSON 数据并将其传递给 Python 的 json 库。

这是我为测试它所做的代码:

import json
from pathlib import Path


def header_to_json(file: Path):
    raw_data = file.read_bytes()
    preamble = raw_data[:6]
    header_len = int.from_bytes(raw_data[6:10], 'little')
    json_start = 10
    json_stop = header_len + 10
    return json.loads(raw_data[json_start:json_stop])


def main():
    file_root = Path.home().joinpath('Downloads', 'osc_files')
    good_file = file_root.joinpath('good.bin')
    bad_file = file_root.joinpath('bad.bin')
    for file in (good_file, bad_file):
        print(f"
Processing {file.name}")
        json_data = header_to_json(file)
        print(f"	Sample data length: {json_data['SAMPLE']['DATALEN']}")
        print(f"	Sample Rate: {json_data['SAMPLE']['SAMPLERATE']}")
        for channel in json_data['CHANNEL']:
            print(f"	{channel['NAME']} Scale: {channel['SCALE']}")
        # print(json.dumps(json_data, indent=4))


if __name__ == '__main__':
    main()

它给出了以下输出:


Processing good.bin
    Sample data length: 1520
    Sample Rate: (100MS/s)
    CH1 Scale: 200mV
    CH2 Scale: 100mV

Processing bad.bin
    Sample data length: 1520
    Sample Rate: (100MS/s)
    CH1 Scale: 2.00V
    CH2 Scale: 200mV

【讨论】:

    猜你喜欢
    • 2023-04-06
    • 1970-01-01
    • 2018-08-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多