5.1 二进制数据
在 Python 中处理二进制文件和处理文本文件有点不同,因为二进制文件包含的是不适合人类阅读的格式。二进制文件处理的是字节,而不是字符串。
处理二进制文件使用 open()
函数,模式里要包含字母
'b'
(比如 'rb'
用于读取,
'wb'
用于写入等等)。
打开二进制文件的例子:
- 读取:
'rb'
- 写入:
'wb'
- 追加:
'ab'
- 读写:
'r+b'
,'w+b'
,'a+b'
例子:
file = open('example.bin', 'rb')
content = file.read()
print(content)
file.close()
变量 'content'
会包含字节数组。
二进制数据(字节)是最底层和最基础的数据表示。任何数据都可以被读取为二进制。
这意味着文本文件总是可以被读取为二进制,但不是所有的二进制文件都可以被解释为文本。
5.2 读取二进制文件
读取整个文件内容
方法 read()
会以字节的形式读取整个文件内容。
例子:
file = open('example.bin', 'rb')
content = file.read()
print(content)
file.close()
读取指定数量的字节
方法 read(n)
会从文件读取 n
个字节。
例子:
file = open('example.bin', 'rb')
content = file.read(10) # 读取前10个字节
print(content)
file.close()
逐行读取
方法 readline()
读取文件的一行。在二进制文件的情况下,行以换行符 (\n)
结束。
例子:
file = open('example.bin', 'rb')
line = file.readline()
print(line)
file.close()
读取所有行
方法 readlines()
读取文件的所有行并以字节列表的形式返回。
例子:
file = open('example.bin', 'rb')
lines = file.readlines()
for line in lines:
print(line)
file.close()
如果你读取的文件不是文本,比如压缩文件、图片或视频,字符串操作方法可能无法正常工作。
5.3 写入二进制数据
方法 write()
将字节写入文件。要写入的数据必须是字节 (bytes)
。
读取和写入图像
从文件读取图像并将其写入另一个文件。
# 读取图像
with open('input_image.jpg', 'rb') as infile:
image_data = infile.read()
# 写入图像
with open('output_image.jpg', 'wb') as outfile:
outfile.write(image_data)
同样也可以写入文本数据:
例子:
data = b"Hello, World!"
lines = [b"First line.\n", b"Second line.\n", b"Third line.\n"]
file = open('example.bin', 'wb')
file.write(data)
file.writelines(lines)
file.close()
GO TO FULL VERSION