Python如何从文件读取原始二进制文件? (音频/视频/文字) [英] Python how to read raw binary from a file? (audio/video/text)

查看:368
本文介绍了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如何从文件读取原始二进制文件? (音频/视频/文字)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆