在这段代码中,使用Python的“wb”是什么意思?

2024-04-19 18:56:48 发布

您现在位置:Python中文网/ 问答频道 /正文

代码:

file('pinax/media/a.jpg', 'wb')

Tags: 代码mediafilejpgwbpinax
3条回答

wb表示文件是以二进制模式打开的。

以二进制模式编写时,Python在将数据写入文件时不会对其进行任何更改。在文本模式下(当b被排除在w之外,或者当您使用wt指定文本模式时),Python将基于默认文本编码对文本进行编码。此外,Python将把行结尾(\n)转换为平台特定的行结尾,这将损坏二进制文件,如exepng文件。

因此,在写入文本文件时应使用文本模式(无论是使用纯文本还是基于文本的格式,如CSV),而在写入非文本文件(如图像)时必须使用二进制模式。

参考文献:

https://docs.python.org/3/tutorial/inputoutput.html#reading-and-writing-fileshttps://docs.python.org/3/library/functions.html#open

这是打开文件的模式。 “w b”表示您正在写入文件(w),并且您正在以二进制模式(b)写入。

查看文档了解更多信息:clicky

File mode,写入和二进制。既然你在写一个.jpg文件,看起来很不错。

但是如果你想读那个jpg文件,你需要使用'rb'

更多信息

On Windows, 'b' appended to the mode opens the file in binary mode, so there are also modes like 'rb', 'wb', and 'r+b'. Python on Windows makes a distinction between text and binary files; the end-of-line characters in text files are automatically altered slightly when data is read or written. This behind-the-scenes modification to file data is fine for ASCII text files, but it’ll corrupt binary data like that in JPEG or EXE files.

相关问题 更多 >