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如何从文件中读取原始二进制文件?(音频/视


基础教程推荐
- 包装空间模型 2022-01-01
- 无法导入 Pytorch [WinError 126] 找不到指定的模块 2022-01-01
- PermissionError: pip 从 8.1.1 升级到 8.1.2 2022-01-01
- 修改列表中的数据帧不起作用 2022-01-01
- 在同一图形上绘制Bokeh的烛台和音量条 2022-01-01
- 在Python中从Azure BLOB存储中读取文件 2022-01-01
- 使用大型矩阵时禁止 Pycharm 输出中的自动换行符 2022-01-01
- Plotly:如何设置绘图图形的样式,使其不显示缺失日期的间隙? 2022-01-01
- PANDA VALUE_COUNTS包含GROUP BY之前的所有值 2022-01-01
- 求两个直方图的卷积 2022-01-01