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

Read a file and write the file's binary to a text document

我正在使用 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)

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