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

问题:使用Python,“ wb”在此代码中是什么意思?

码:

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

Code:

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

回答 0

文件模式,写入和二进制。由于您正在编写.jpg文件,因此看起来不错。

但是,如果您应该阅读该jpg文件,则需要使用 'rb'

更多信息

在Windows上,附加到模式的’b’以二进制模式打开文件,因此也有’rb’,’wb’和’r + b’之类的模式。Windows上的Python区分文本文件和二进制文件。当读取或写入数据时,文本文件中的行尾字符会自动更改。这种对文件数据的幕后修改对于ASCII文本文件而言是很好的选择,但它会破坏JPEG或EXE文件中的二进制数据。

File mode, write and binary. Since you are writing a .jpg file, it looks fine.

But if you supposed to read that jpg file you need to use 'rb'

More info

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.


回答 1

wb指示文件被打开以二进制方式写作。

当以二进制模式写入时,Python在写入文件时不会对数据进行任何更改。但是,在文本模式下(bw或在用或指定文本模式时排除时wt),Python将基于默认文本编码对文本进行编码。此外,Python会将行尾(\n)转换为特定于平台的行尾,这会破坏二进制文件(例如exepng文件)。

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

参考文献:

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

The wb indicates that the file is opened for writing in binary mode.

When writing in binary mode, Python makes no changes to data as it is written to the file. In text mode (when the b is excluded as in just w or when you specify text mode with wt), however, Python will encode the text based on the default text encoding. Additionally, Python will convert line endings (\n) to whatever the platform-specific line ending is, which would corrupt a binary file like an exe or png file.

Text mode should therefore be used when writing text files (whether using plain text or a text-based format like CSV), while binary mode must be used when writing non-text files like images.

References:

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


回答 2

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

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

That is the mode with which you are opening the file. “wb” means that you are writing to the file (w), and that you are writing in binary mode (b).

Check out the documentation for more: clicky