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如何从文件中读取原始二进制文件?(音频/视
- padding='same' 转换为 PyTorch padding=# 2022-01-01
- 如何在 Python 的元组列表中对每个元组中的第一个值求和? 2022-01-01
- pytorch 中的自适应池是如何工作的? 2022-07-12
- 如何在 python3 中将 OrderedDict 转换为常规字典 2022-01-01
- 分析异常:路径不存在:dbfs:/databricks/python/lib/python3.7/site-packages/sampleFolder/data; 2022-01-01
- 沿轴计算直方图 2022-01-01
- python check_output 失败,退出状态为 1,但 Popen 适用于相同的命令 2022-01-01
- 使用Heroku上托管的Selenium登录Instagram时,找不到元素';用户名'; 2022-01-01
- 如何将一个类的函数分成多个文件? 2022-01-01
- python-m http.server 443--使用SSL? 2022-01-01