读取文件并将文件的二进制文件写入文本文档



我正在使用Python 3.10,我正在尝试读取Windows可执行文件,并以文本格式(1和0)输出二进制数据到文本文件中。我只需要二进制,我不想要偏移量和字节的ASCII表示。我不需要任何空格或新行。

total = ""
with open("input.exe", "rb") as f:
while (byte := f.read(1)):
total = total + byte.decode("utf-8")
with open("output.txt", "w") as o:
o.write(total)

但是,它不工作,我呈现以下错误:

Traceback (most recent call last):
File "converter.py", line 4, in <module>
total = total + byte.decode("utf-8")
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x90 in position 0: invalid start byte

这段代码应该按您的要求执行:

with open("input.exe", "rb") as f:
buf = f.read()
with open("output.txt", "w") as o:
binary = bin(int.from_bytes(buf, byteorder='big'))[2:] # or byteorder='little' as necessary
o.write(binary)

注意,当处理非常大的文件时,它可能会占用内存。

最新更新