【问题标题】:Error while writing an array of bytes to a File in python在python中将字节数组写入文件时出错
【发布时间】:2021-08-01 10:25:04
【问题描述】:
Input Byte array = [b'\x03\x00', b'\x04\x00', b'\x05\x00', b'\x05\x00', b'\x05\x00', b'\x06\x00', b'\x07\x00', 
b'\x08\x00', b'\t\x00', b'\n\x00', b'\t\x00', b'\x08\x00', b'\x07\x00', b'\x06\x00']

我需要将上述数组写入二进制文件并验证数据是否正确写入,我正在读回同一个文件。但是在回读时,它给了我一个空列表。有人可以在这里指出错误吗?

#Values array is calculated from the previous steps
intermediate = [int.from_bytes(x, byteorder='big', signed=True) for x in values]
print("Integer in Big Endian {}".format(intermediate))

fileData = [byte.to_bytes(2, byteorder='little', signed=True) for byte in intermediate]
print("Data written to the Binary file{}".format(fileData))
#I am printing the array of bytes that I am writing to the file.


newFile = open('./flash.dat', "wb")
for byte in intermediate:
    newFile.write(byte.to_bytes(2, byteorder='little', signed=True))


file = open("./flash.dat", "rb")
number=file.read()
file.close()
print("Data in the binary file {}".format(number))

结果是这样的

 Integer in Big Endian [3, 4, 5, 5, 5, 6, 7, 8, 9, 10, 9, 8, 7, 6]
 Data written to the Binary file[b'\x03\x00', b'\x04\x00', b'\x05\x00', b'\x05\x00', b'\x05\x00', b'\x06\x00', 
 b'\x07\x00', b'\x08\x00', b'\t\x00', b'\n\x00', b'\t\x00', b'\x08\x00', b'\x07\x00', b'\x06\x00']
 Data in the binary file b''

【问题讨论】:

    标签: python python-3.x byte


    【解决方案1】:

    您没有刷新文件(更改保留在内存中,它们永远不会保存到磁盘)。

    newFile = open('./flash.dat', "wb")
    for byte in intermediate:
        newFile.write(byte.to_bytes(2, byteorder='little', signed=True))
    # save to disk
    newFile.flush()
    # or close the file (this also flush the change to disk)
    newFile.close()
    

    或者更好,context manager:

    # If we use the with (context manager) it automatically flushes and closes the file
    with open('./flash.dat', "wb") as new_file:
        for byte in intermediate:
            new_file.write(byte.to_bytes(2, byteorder='little', signed=True))
    
    # the same for reading the file
    with open("./flash.dat", "rb") as file:
        number=file.read()
    
    print("Data in the binary file {}".format(number))
    # Data in the binary file b'\x00\x03\x00\x04\x00\x05\x00\x05\x00\x05\x00\x06\x00\x07\x00\x08\x00\t\x00\n\x00\t\x00\x08\x00\x07\x00\x06'
    

    另外:你不应该使用 camelCase。在 python 中是从不使用的(看pep08)。

    而不是newFile 使用new_filefileData 使用file_data

    【讨论】:

      【解决方案2】:

      您需要在写入文件后关闭文件,然后才能再次打开它。由于缓冲,文件可能不会被写入磁盘,直到它被关闭或缓冲区被刷新。关闭文件会刷新缓冲区并将其写入磁盘。

      newFile = open('./flash.dat', "wb")
      for byte in intermediate:
          newFile.write(byte.to_bytes(2, byteorder='little', signed=True))
      newFile.close()
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2014-04-10
        • 2015-09-04
        • 2019-02-07
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多