Python基础教程

004_Python读写二进制文件

Python读写二进制文件

Python读写二进制文件主要方法

Python读写二进制文件常用的方法有:

  • open():打开二进制文件对象,模式中有"b"
  • f.close():关闭资源
  • f.write():写入字节串
  • f.seek():移动到指定位置开始读取字节串
  • f.tell():返回当前读取的位置
  • f.flush():主动刷新缓冲

二进制文件读写对应于字节串(bytes类型),相关处理函数模块有struct和binascii等。

Python读写二进制文件示例

myfname="bfile"

with open(myfname,"wb") as f:                    # 写文件时指定模式为"b"
    astr="hello北京"
    abytes=astr.encode("utf-8")                  # 字符串转字节串,需要指定编码方式
    print(abytes)
    f.write(abytes)

with open(myfname,"r",encoding="utf-8") as fd:   # 打开文件时指定编码为utf-8
    abytes=fd.read()                             # 用utf-8的方式读取二进制文件(实际上所有的文件存储形式都是二进制)
    print(abytes)

with open(myfname,"rb") as fd:                   # 打开二进制文件
    abytes=fd.read()                             # 读取二进制内容到字节串中
    print(abytes)
    print(abytes.decode("utf-8"))                # 二进制字节转为(翻译)字符

运行结果

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t06.py
b'helloxe5x8cx97xe4xbaxac'
hello北京
b'helloxe5x8cx97xe4xbaxac'
hello北京

Process finished with exit code 0

二进制文件的随机读取

二进制文件一般是连续存储,其中没有空白。因此,随机读取(读取任意指定位置)数据时,需要知道此位置离起始位置的偏移字节数,以及读取的字节长度。

seek() 方法语法如下:

f.seek(offset[, whence])

说明:

  • offset -- 开始的偏移量,也就是代表需要移动偏移的字节数,如果是负数表示从倒数第几位开始。
  • whence:可选,默认值为 0。给 offset 定义一个参数,表示要从哪个位置开始偏移;0 代表从文件开头开始算起,1 代表从当前位置开始算起,2 代表从文件末尾算起。

返回值:

如果操作成功,则返回新的文件位置,如果操作失败,则函数返回 -1。

示例程序如下

myfname="bfile"

with open(myfname,"wb") as f:                     # 写文件时指定模式为"b"
    astr="hello北京"
    abytes=astr.encode("utf-8")                   # 字符串转字节串,需要指定编码方式
    print(abytes)
    f.write(abytes)

with open(myfname,"rb") as fd:                    # 打开二进制文件
    abytes=fd.read(2)                             # 读取二进制内容到字节串中
    print(abytes)
    print(abytes.decode("utf-8"))
    pos=fd.tell()                                 # 获取当前操作位置
    print(pos)
    fd.seek(5,0)                                  # 从起始位置,偏移5个字节位置
    abytes2 =fd.read(3)                           # 从偏移后的位置开始读取3个字节
    print(abytes2)                                # 输出3个字节
    print(abytes2.decode("utf-8"))                # 将字节串翻译成字符串

运行结果

C:UsershccmaAnaconda3python.exe E:/wkp01/p00/test01/atestpkg/t06.py
b'helloxe5x8cx97xe4xbaxac'
b'he'
he
2
b'xe5x8cx97'
北

Process finished with exit code 0
这篇文章对您有用吗? 2

我们要如何帮助您?