python中的如何读取.bin文件

2025-09-24 07:29:51

1、打开sublime text3编辑器,新建一个py文档

python中的如何读取.bin文件

2、file = open("bootfix.bin")

file.read()

file.close()

这里我用最基本的语法来打开文件,然后读取。

这个时候出现错误,那是因为bin文件是二进制的。

python中的如何读取.bin文件

3、file = open("bootfix.bin", "rb")

实际上我们要读取二进制文件,需要加上rb来进行打开。

这个时候可以看到二进制的文件了。

python中的如何读取.bin文件

4、import os

file = open("E:\\bootfix.bin", "rb")

在实际操作中,可能文件和py文件不在同一个文件夹里面,那么填写绝对路径就要引入os模块了。

python中的如何读取.bin文件

5、with open("E:\\bootfix.bin", "rb") as file:

    line = file.readline()

    print(line)

为了避免忘记写上关闭文件的代码,可以用with open的格式来书写。

python中的如何读取.bin文件

6、import os

with open("E:\\bootfix.bin", "rb") as file:

    for line in file:

        print(line, end="")

为了查看方便,我们还可以用for循环来进行循环陆续读取。

python中的如何读取.bin文件

声明:本网站引用、摘录或转载内容仅供网站访问者交流或参考,不代表本站立场,如存在版权或非法内容,请联系站长删除,联系邮箱:site.kefu@qq.com。
猜你喜欢