What does 'wb' mean in this code, using Python?

PythonFileSyntax

Python Problem Overview


Code:

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

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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

Solution 3 - Python

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][1]

[1]: http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files "docs"

Solution 4 - Python

Yeah, many peoples getting confuse to understand what is "b"; Actually in computer programming having various data type; "b" is 'byte' data type and it's 8 bits long; When you open an image file you can see "{ 0xFF, 0xF0, 0x0F, 0x11 }" this kinds of text and it's byte data; yes that's right "b" means binary data but another mean of "b" is 'byte' data in Python "wb" means "write+byte"..

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionzjm1126View Question on Stackoverflow
Solution 1 - PythonYOUView Answer on Stackoverflow
Solution 2 - PythonDaniel GView Answer on Stackoverflow
Solution 3 - PythonGlenCrawfordView Answer on Stackoverflow
Solution 4 - PythonTechno TMView Answer on Stackoverflow