搜索
首页后端开发Python教程怎么使用Python读写二进制文件

1. 简介

Python 读写文件的二进制数据需要使用到struct模块,进行C/C++与Python数据格式的转换。

2. struct模块介绍

struct模块中最常用的函数为pack和unpack,用法如下:

函数 return explain
pack(fmt,v1,v2…) string 按照给定的格式(fmt),把数据转换成字符串(字节流),并将该字符串返回.
pack_into(fmt,buffer,offset,v1,v2…) None 按照给定的格式(fmt),将数据转换成字符串(字节流),并将字节流写入以offset开始的buffer中.(buffer为可写的缓冲区,可用array模块)
unpack(fmt,v1,v2……) tuple 按照给定的格式(fmt)解析字节流,并返回解析结果
pack_from(fmt,buffer,offset) tuple 按照给定的格式(fmt)解析以offset开始的缓冲区,并返回解析结果
calcsize(fmt) size of fmt 计算给定的格式(fmt)占用多少字节的内存,注意对齐方式

3. struct模块中数据格式fmt对应C/C++和Python中的类型

Format C Type Python type Standard size
x pad byte no value
c char string of length 1
b signed char integer 1
B unsigned char integer 1
? _Bool bool 1
h short integer 2
H unsigned short integer 2
i int integer 4
I unsigned int integer 4
l long integer 4
L unsigned long integer 4
q long long integer 8
Q unsigned long long integer 8
f float float 4
d double float 8
s char[] string
p char[] string
P void * integer

4. 实例

注意:代码中,044f6b14ab790ac651be3024bec5f806表示大端

import struct

# 打开文件
with open("binary_file.bin", "wb") as f:

    # 写入4个字节的整数(值为12345)
    int_value = 12345
    f.write(struct.pack("<i", int_value))

    # 写入8个字节的双精度浮点数(值为3.14159)
    double_value = 3.14159
    f.write(struct.pack("<d", double_value))

    # 写入一个字节的布尔值(值为True)
    bool_value = True
    f.write(struct.pack("<?", bool_value))

    # 写入一个定长字符串(10个字符,值为"hello")
    string_value = "hello".encode("utf-8")
    f.write(struct.pack("<5s", string_value))

    # 写入一个定长字节数组(20个字节,值为b"\x01\x02\x03...\x14")
    byte_array_value = bytes(range(1, 21))
    f.write(struct.pack("<20s", byte_array_value))

    f.close()

# 打开文件
with open("binary_file.bin", "rb") as f:

    # 读取4个字节,解析成一个整数
    int_value = struct.unpack("<i", f.read(4))[0]
    
    # 读取8个字节,解析成一个双精度浮点数
    double_value = struct.unpack("<d", f.read(8))[0]

    # 读取一个字节,解析成一个布尔值
    bool_value = struct.unpack("<?", f.read(1))[0]

    # 读取一个字符串,解析成一个定长字符串(10个字符)
    string_value = struct.unpack("<5s", f.read(5))[0].decode("utf-8")

    # 读取一个字节数组,解析成一个定长字节数组(20个字节)
    byte_array_value = struct.unpack("<20s", f.read(20))[0]

    # 打印结果
    print(f"int_value: {int_value}")
    print(f"double_value: {double_value}")
    print(f"bool_value: {bool_value}")
    print(f"string_value: {string_value}")
    print(f"byte_array_value: {byte_array_value}")

    f.close()

5. Python 字符串前面加u,r,b,f的含义

5.1. 字符串前加u

后面字符串以 Unicode格式进行编码,一般用在中文字符串前面,防止因为源码储存格式问题,导致再次使用时出现乱码。

str= u&#39;hello&#39;

5.2. 字符串前加r

去掉反斜杠的转移机制。(特殊字符:即那些,反斜杠加上对应字母,表示对应的特殊含义的,比如最常见的”\n”表示换行,”\t”表示Tab等。 )

str= r&#39;hello\n\t\n&#39;

5.3. 字符串前加b

表示该字符串是bytes 类型。

bytes = b&#39;hello&#39;

在 Python3 中,bytes 和 str 的互相转换方式是

str.encode(‘utf-8&#39;)
bytes.decode(‘utf-8&#39;)

5.4. 字符串前加f

以 f 开头表示在字符串内支持大括号内的python 表达式,字符串拼接

name = &#39;Lily&#39;
print(f&#39;My name is {name}.&#39;)

以上是怎么使用Python读写二进制文件的详细内容。更多信息请关注PHP中文网其他相关文章!

声明
本文转载于:亿速云。如有侵权,请联系admin@php.cn删除
Python的科学计算中如何使用阵列?Python的科学计算中如何使用阵列?Apr 25, 2025 am 12:28 AM

Arraysinpython,尤其是Vianumpy,ArecrucialInsCientificComputingfortheireftheireffertheireffertheirefferthe.1)Heasuedfornumerericalicerationalation,dataAnalysis和Machinelearning.2)Numpy'Simpy'Simpy'simplementIncressionSressirestrionsfasteroperoperoperationspasterationspasterationspasterationspasterationspasterationsthanpythonlists.3)inthanypythonlists.3)andAreseNableAblequick

您如何处理同一系统上的不同Python版本?您如何处理同一系统上的不同Python版本?Apr 25, 2025 am 12:24 AM

你可以通过使用pyenv、venv和Anaconda来管理不同的Python版本。1)使用pyenv管理多个Python版本:安装pyenv,设置全局和本地版本。2)使用venv创建虚拟环境以隔离项目依赖。3)使用Anaconda管理数据科学项目中的Python版本。4)保留系统Python用于系统级任务。通过这些工具和策略,你可以有效地管理不同版本的Python,确保项目顺利运行。

与标准Python阵列相比,使用Numpy数组的一些优点是什么?与标准Python阵列相比,使用Numpy数组的一些优点是什么?Apr 25, 2025 am 12:21 AM

numpyarrayshaveseveraladagesoverandastardandpythonarrays:1)基于基于duetoc的iMplation,2)2)他们的aremoremoremorymorymoremorymoremorymoremorymoremoremory,尤其是WithlargedAtasets和3)效率化,效率化,矢量化函数函数函数函数构成和稳定性构成和稳定性的操作,制造

阵列的同质性质如何影响性能?阵列的同质性质如何影响性能?Apr 25, 2025 am 12:13 AM

数组的同质性对性能的影响是双重的:1)同质性允许编译器优化内存访问,提高性能;2)但限制了类型多样性,可能导致效率低下。总之,选择合适的数据结构至关重要。

编写可执行python脚本的最佳实践是什么?编写可执行python脚本的最佳实践是什么?Apr 25, 2025 am 12:11 AM

到CraftCraftExecutablePythcripts,lollow TheSebestPractices:1)Addashebangline(#!/usr/usr/bin/envpython3)tomakethescriptexecutable.2)setpermissionswithchmodwithchmod xyour_script.3)

Numpy数组与使用数组模块创建的数组有何不同?Numpy数组与使用数组模块创建的数组有何不同?Apr 24, 2025 pm 03:53 PM

numpyArraysareAreBetterFornumericalialoperations andmulti-demensionaldata,而learthearrayModuleSutableforbasic,内存效率段

Numpy数组的使用与使用Python中的数组模块阵列相比如何?Numpy数组的使用与使用Python中的数组模块阵列相比如何?Apr 24, 2025 pm 03:49 PM

numpyArraySareAreBetterForHeAvyNumericalComputing,而lelethearRayModulesiutable-usemoblemory-connerage-inderabledsswithSimpleDatateTypes.1)NumpyArsofferVerverVerverVerverVersAtility andPerformanceForlargedForlargedAtatasetSetsAtsAndAtasEndCompleXoper.2)

CTYPES模块与Python中的数组有何关系?CTYPES模块与Python中的数组有何关系?Apr 24, 2025 pm 03:45 PM

ctypesallowscreatingingangandmanipulatingc-stylarraysinpython.1)usectypestoInterfacewithClibrariesForperfermance.2)createc-stylec-stylec-stylarraysfornumericalcomputations.3)passarraystocfunctions foreforfunctionsforeffortions.however.however,However,HoweverofiousofmemoryManageManiverage,Pressiveo,Pressivero

See all articles

热AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover

AI Clothes Remover

用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool

Undress AI Tool

免费脱衣服图片

Clothoff.io

Clothoff.io

AI脱衣机

Video Face Swap

Video Face Swap

使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热工具

SecLists

SecLists

SecLists是最终安全测试人员的伙伴。它是一个包含各种类型列表的集合,这些列表在安全评估过程中经常使用,都在一个地方。SecLists通过方便地提供安全测试人员可能需要的所有列表,帮助提高安全测试的效率和生产力。列表类型包括用户名、密码、URL、模糊测试有效载荷、敏感数据模式、Web shell等等。测试人员只需将此存储库拉到新的测试机上,他就可以访问到所需的每种类型的列表。

mPDF

mPDF

mPDF是一个PHP库,可以从UTF-8编码的HTML生成PDF文件。原作者Ian Back编写mPDF以从他的网站上“即时”输出PDF文件,并处理不同的语言。与原始脚本如HTML2FPDF相比,它的速度较慢,并且在使用Unicode字体时生成的文件较大,但支持CSS样式等,并进行了大量增强。支持几乎所有语言,包括RTL(阿拉伯语和希伯来语)和CJK(中日韩)。支持嵌套的块级元素(如P、DIV),

SublimeText3 Linux新版

SublimeText3 Linux新版

SublimeText3 Linux最新版

记事本++7.3.1

记事本++7.3.1

好用且免费的代码编辑器

DVWA

DVWA

Damn Vulnerable Web App (DVWA) 是一个PHP/MySQL的Web应用程序,非常容易受到攻击。它的主要目标是成为安全专业人员在合法环境中测试自己的技能和工具的辅助工具,帮助Web开发人员更好地理解保护Web应用程序的过程,并帮助教师/学生在课堂环境中教授/学习Web应用程序安全。DVWA的目标是通过简单直接的界面练习一些最常见的Web漏洞,难度各不相同。请注意,该软件中