Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python file IO 'w' vs 'wb' [duplicate]

Wondering what the real difference is when writing files from Python. From what I can see if I use w or wb I am getting the same result with text.

I thought that saving as a binary file would show only binary values in a hex editor, but it also shows text and then ASCII version of that text.

Can both be used interchangably when saving text? (Windows User)

like image 431
pj2452 Avatar asked Apr 01 '13 19:04

pj2452


People also ask

Does WB overwrite file Python?

w : Opens in write-only mode. The pointer is placed at the beginning of the file and this will overwrite any existing file with the same name. It will create a new file if one with the same name doesn't exist. wb : Opens a write-only file in binary mode.

What is MODE =' W b in 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.

What is the difference between WB and WB+ in Python?

Explanation: wb mode is used to open binary file in write mode and wb+ mode open binary file both for read and write operation.

What is mean by the file mode W+?

w+: Opens a file in read and write mode. It creates a new file if it does not exist, if it exists, it erases the contents of the file and the file pointer starts from the beginning. rw+: Opens a file in read and write mode. File pointer starts at the beginning of the file.


1 Answers

Only in Windows, in the latter case, .write('\n') writes one byte with a value of 10. In the former case, it writes two bytes, with the values 13 and 10.

You can prove this to yourself by looking at the resulting file size, and examining the files in a hex editor.

In POSIX-related operating systems (UNIX, SunOS, MacOS, Linux, etc.), there is no difference beetween 'w' and 'wb'.

like image 53
Robᵩ Avatar answered Oct 10 '22 06:10

Robᵩ