Python how to read raw binary from a file? (audio/video/text)(Python如何从文件中读取原始二进制文件?(音频/视频/文本))
问题描述
我想读取文件的原始二进制文件并将其放入字符串中.目前我正在打开一个带有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如何从文件中读取原始二进制文件?(音频/视频/文本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持编程学习网!
本文标题为:Python如何从文件中读取原始二进制文件?(音频/视


基础教程推荐
- matplotlib 设置 yaxis 标签大小 2022-01-01
- 对多索引数据帧的列进行排序 2022-01-01
- 在 Django Admin 中使用内联 OneToOneField 2022-01-01
- Python 中是否有任何支持将长字符串转储为块文字或折叠块的 yaml 库? 2022-01-01
- kivy 应用程序中的一个简单网页作为小部件 2022-01-01
- 在 Python 中将货币解析为数字 2022-01-01
- Kivy 使用 opencv.调整图像大小 2022-01-01
- 比较两个文本文件以找出差异并将它们输出到新的文本文件 2022-01-01
- 究竟什么是“容器"?在蟒蛇?(以及所有的 python 容器类型是什么?) 2022-01-01
- Python,确定字符串是否应转换为 Int 或 Float 2022-01-01