0

Can someone explain binary mode and the usage of it (with an example if you don't mind) to me?

13th Sep 2016, 2:30 PM
DELETED
2 Réponses
+ 2
On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files. -- This is not quite right. In Python 3, reading from a text file gets you text. Reading from a binary file gets you byte arrays. (and I don't quite remember how it is in Py2) The effect is not restricted by end-of-line characters only; mode affects how the data is represented overall. So, Keyatta, use the mode according to the data you're going to read or write. If it's binary data (a serialized object, an image, an audio file), use binary. If it's text, use text.
13th Sep 2016, 10:27 PM
trueneu
trueneu - avatar
+ 1
https://docs.python.org/2/tutorial/inputoutput.html 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. Be very careful to use binary mode when reading and writing such files. On Unix, it doesn’t hurt to append a 'b' to the mode, so you can use it platform-independently for all binary files.
13th Sep 2016, 2:57 PM
Zen
Zen - avatar