调用mmap write()方法会在python(Windows)中向mmap文件添加额外字符

2024-10-02 22:38:19 发布

您现在位置:Python中文网/ 问答频道 /正文

我真的很迷茫以下问题

我不断更新json_数据,为了将其写回内存映射文件,我需要将其转换为字节

出于某些特殊原因,它似乎在向包含json数据的内存映射文件中添加额外的“}”。我真的不明白为什么会这样

# Open the mmap file
        json_file = open(json_path, "r+", encoding="utf-8")

        mapped_file = mmap.mmap(json_file.fileno(), 1024, access=mmap.ACCESS_WRITE)

        result = buffer_for_json.decode("utf-8").rstrip('\0')

        # Content is JSON, so load it
        json_data = json.loads(result)

# Later in code some modifications are made to the json_data
# ..some code here

    json_string = json.dumps(json_data)
    bytes_written = mappedFile.write(json_string.encode('utf-8')) # This part is having issues

    # Flush content to disk
    mappedFile.flush()

我已经验证了encode()的json_字符串没有额外的“}”。出于某种原因,bytes_written = mappedFile.write(json_string.encode('utf-8'))行似乎添加了一个额外的“}”

任何解决此问题的建议都将不胜感激


Tags: 文件the数据内存jsondatastringis