我想读取文件的原始二进制文件并将其放入字符串中.目前我正在打开一个带有rb"标志的文件并打印字节,但它以 ASCII 字符的形式出现(对于文本,即对于视频和音频文件,它会给出符号和乱码).如果可能的话,我想得到原始的 0 和 1.这也需要适用于音频和视频文件,因此不能简单地将 ascii 转换为二进制.
I want to read the raw binary of a file and put it into a string. Currently I am opening a file with the "rb" flag and printing the byte but it's coming up as ASCII characters (for text that is, for video and audio files it's giving symbols and gibberish). I'd like to get the raw 0's and 1's if possible. This needs to work for audio and video files as well so simply converting the ascii to binary isn't an option.
with open(filePath, "rb") as file:
byte = file.read(1)
print byte
要获得二进制表示我认为你需要导入 binascii,然后:
to get the binary representation I think you will need to import binascii, then:
byte = f.read(1)
binary_string = bin(int(binascii.hexlify(byte), 16))[2:].zfill(8)
或者,分解:
import binascii
filePath = "mysong.mp3"
file = open(filePath, "rb")
with file:
byte = file.read(1)
hexadecimal = binascii.hexlify(byte)
decimal = int(hexadecimal, 16)
binary = bin(decimal)[2:].zfill(8)
print("hex: %s, decimal: %s, binary: %s" % (hexadecimal, decimal, binary))
将输出:
hex: 64, decimal: 100, binary: 01100100
这篇关于Python如何从文件中读取原始二进制文件?(音频/视频/文本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!