如何在Python中逐字节读取文件以及如何将bytelist打印为二进制文件? [英] How to read a file byte by byte in Python and how to print a bytelist as a binary?
问题描述
$ $ $ $ $ $ $ $ $ $ $ $ $' :
byte = file.read(8)
#做某事...
<那么这是否使变量字节在每个循环的开头都包含8个下一位?这些字节实际上并不重要。唯一重要的是我需要读取一个8位堆栈文件。
编辑:
我也收集这些字节在列表中,我想要打印它们,以便他们不打印出ASCII字符,但作为原始字节,即当我打印bytelist它给出的结果为
['10010101','00011100',....]
$为了回答你的问题的第二部分,要转换为二进制文件,你可以使用 format string 和
>>>> byte ='a'
>>>格式(ord(byte))
'01100001'
请注意格式垫与正确数量的前导零,这似乎是您的要求。此方法需要Python 2.6或更高版本。
I'm trying to read a file byte by byte, but I'm not sure how to do that. I'm trying to do it like that:
file = open(filename, 'rb')
while 1:
byte = file.read(8)
# Do something...
So does that make the variable byte to contain 8 next bits at the beginning of every loop? It doesn't matter what those bytes really are. The only thing that matters is that I need to read a file in 8-bit stacks.
EDIT:
Also I collect those bytes in a list and I would like to print them so that they don't print out as ASCII characters, but as raw bytes i.e. when I print that bytelist it gives the result as
['10010101', '00011100', .... ]
To answer the second part of your question, to convert to binary you can use a format string and the ord
function:
>>> byte = 'a'
>>> '{0:08b}'.format(ord(byte))
'01100001'
Note that the format pads with the right number of leading zeros, which seems to be your requirement. This method needs Python 2.6 or later.
这篇关于如何在Python中逐字节读取文件以及如何将bytelist打印为二进制文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!