Python如何从文件中读取原始二进制文件?(音频/视频/文本)

Python how to read raw binary from a file? (audio/video/text)(Python如何从文件中读取原始二进制文件?(音频/视频/文本))
本文介绍了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如何从文件中读取原始二进制文件?(音频/视频/文本)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持跟版网!

本站部分内容来源互联网,如果有图片或者内容侵犯您的权益请联系我们删除!

相关文档推荐

How to find element by part of its id name in selenium with python(如何使用python在selenium中通过其id名称的一部分查找元素)
NoSuchElementException: Message: Unable to locate element while trying to click on the button VISA through Selenium and Python(NoSuchElementException:消息:尝试通过 Selenium 和 Python 单击 VISA 按钮时无法找到元素) - IT屋-程序员软件开发技术分
Selenium not able to click on Get Data button on using Python(Selenium 在使用 Python 时无法单击“获取数据按钮)
selenium.common.exceptions.ElementClickInterceptedException: Message: element click intercepted: Element is not clickable with Selenium and Python(selenium.common.exceptions.ElementClickInterceptedException:消息:元素点击被拦截:元素不可点击
Selenium Compound class names not permitted(不允许使用硒化合物类名称)
selenium.common.exceptions.NoSuchElementException: Message: no such element: Unable to locate element while trying to click Next button with selenium(selenium.common.exceptions.NoSuchElementException:消息:没有这样的元素:尝试使用 selenium 单