python读写二进制文件(读写字节数据)

Posted Data+Science+Insight

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python读写二进制文件(读写字节数据)相关的知识,希望对你有一定的参考价值。

python读写二进制文件(读写字节数据)

你想读写二进制文件,比如图片,声音文件等就是常见的二进制文件。

使用模式为 rb 或 wb 的 open() 函数来读取或写入二进制数据。比如:

# Read the entire file as a single byte string
with open(\'somefile.bin\', \'rb\') as f:
    data = f.read()

# Write binary data to a file
with open(\'somefile.bin\', \'wb\') as f:
    f.write(b\'Hello World\')

在读取二进制数据时,需要指明的是所有返回的数据都是字节字符串格式的,而不是文本字符串。 类似的,在写入的时候,必须保证参数是以字节形式对外暴露数据的对象(比如字节字符串,字节数组对象等)。

 

# 分别进行数据的读取和写入

Here\'s how to do it with the basic file operations in Python. This opens one file, reads the data into memory, then opens the second file and writes it out.

in_file = open("in-file", "rb"

以上是关于python读写二进制文件(读写字节数据)的主要内容,如果未能解决你的问题,请参考以下文章

python文件读写

java中字节级数据文件的读写编程

C++学习49 对二进制文件的读写操作

逐字节读写以进行压缩

java 中简述使用流进行读写文本文件的步骤?

JAVA中,使用字节流读写文件,为啥找不到文件的位置?请看补充: