简体   繁体   English

python从bin文件中逐字节读取时间太长

[英]python reading byte by byte from bin file takes too long

i am trying to read the bytes from a bin file with the following code: 我正在尝试使用以下代码从bin文件中读取字节:

with open("filedata.bin","rb") as file:
   data = file.read()
   for byte in data:
         print byte

this works fine but the issue is that it takes too long (about 4 minutes). 这可以正常工作,但问题是它花费的时间太长(大约4分钟)。 The goal is to read any byte of the bin file and send them over a serial interface. 目的是读取bin文件的任何字节,然后通过串行接口发送它们。

My file is 101 kByte. 我的文件是101 KB。 Until now i didn't send any data over the serial interface. 直到现在,我还没有通过串行接口发送任何数据。 So this can not be the problem. 因此,这不是问题。 I verify the rate over the python shell with the "print byte". 我使用“打印字节”验证了python shell上的速率。 It prints me the first byte to the last byte. 它把我的第一个字节打印到最后一个字节。

Does someone has an idea how i could read the bytes more quickly? 有人知道我如何更快地读取字节吗?

when using file.read() without any arguments, you read the entire file into memory at once. 当使用不带任何参数的file.read() ,您会立即将整个文件读入内存。 This is often slow. 这通常很慢。

To speed this up, you will want to read the file a few bytes at a time. 为了加快速度,您需要一次读取几个字节的文件。

You can do this is by specifying how many bytes you want to read, for example: 您可以通过指定要读取的字节数来执行此操作,例如:

with open("myfile", "rb") as f:
    byte = f.read(1)
    while byte:
        # do something with the byte
        byte = f.read(1)

A more advanced method to do this is to use the iter function: 一个更高级的方法是使用iter函数:

for i in iter(lambda x: f.read(1), b""):
    # do something with the byte

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM