Python文件字节处理实战:读写、编码与转换详解

码头散步
码头散步
发布时间:2026-10-12| 2人浏览过
原创

本文详细讲解Python中如何使用字节模式处理文件。通过添加mode参数'b',文件方法将返回bytes对象。示例展示了如何识别PNG文件头,以及如何将文件字节流转换为十六进制字符串、Base64编码,并将十六进制数据还原为二进制文件写入,涵盖常见文件处理场景。

在打开文件时,可以在mode参数中加入字符'b'以启用二进制模式。此时,所有适用于文件对象的方法均保持不变,但每种方法的预期输入和返回值均为bytes对象。

>>> with open(`dog_breeds.txt`, 'rb') as reader:
>>>     print(reader.readline())
b'Pug\n'

当以二进制模式打开文件并逐块读取这些字节时,可以验证文件类型。例如,通过读取前几个字节,可以确认该文件确实为PNG格式:

>>> with open('jack_russell.png', 'rb') as byte_reader:
>>>     print(byte_reader.read(1))
>>>     print(byte_reader.read(3))
>>>     print(byte_reader.read(2))
>>>     print(byte_reader.read(1))
>>>     print(byte_reader.read(1))
b'\x89'
b'PNG'
b'\r\n'
b'\x1a'
b'\n'

知识点扩展:

读取文件的字节流数据,将其转换为十六进制数据

def read_file():
    with open('./flag.zip','rb') as file_byte:
        file_hex = file_byte.read().hex()
        print(file_hex)
        write_file(file_hex)

def write_file(file_hex):
    with open('new.txt','w') as new_file:
        new_file.write(file_hex)

if __name__ == '__main__':
    read_file()

读取文件的字节流数据,将其编码为base64并输出

import base64

def read_file():
    with open('./flag.zip','rb') as file_byte:
        file_base64 = base64.b64encode(file_byte.read())
        print(file_base64)

if __name__ == '__main__':
    read_file()

将十六进制文件转化为字节流文件写入

import struct

a = open("str.txt","r")#十六进制数据文件
lines = a.read()
res = [lines[i:i+2] for i in range(0,len(lines),2)]

with open("xxx.xxx","wb") as f:
	for i in res:
		s = struct.pack('B',int(i,16))
		f.write(s)

以上就是python用字节处理文件实例讲解的详细内容,更多关于python使用字节处理文件的资料请关注本站其它相关文章!

免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。

Python 相关产品和应用

全部下载
Selenium

Selenium

4.51.0 · Windows

用于浏览器自动化和 Web 测试的 Python 工具。

scikit-learn

scikit-learn

1.9.1 · Windows

常用 Python 机器学习算法与模型评估工具库。

Black

Black

26.10.1 · Windows

强调一致性的 Python 自动代码格式化工具。

Ruff

Ruff

0.17.1 · macOS

由 Rust 编写的高速 Python 代码检查和格式化工具。

pytest

pytest

9.1.1 · Windows

简洁而强大的 Python 自动化测试框架。

FastAPI

FastAPI

0.146.0 · Windows

高性能 Python API 框架,支持类型提示和自动接口文档。

Flask

Flask

3.1.3 · Windows

轻量灵活的 Python Web 应用框架。

Django

Django

6.1.2 · Windows

成熟的 Python Web 框架,适合构建内容站点和业务系统。

Spyder

Spyder

6.1.7 · Windows

面向科学计算与数据分析的 Python 集成开发环境。

SciPy

SciPy

1.18.1 · Windows

面向科学、工程和技术计算的 Python 算法库。