I am a beginner and I am having trouble in grasping binary files. When I write to a file in binary mode (in python), I just write normal text. There is nothing binary about it. I know every file on my computer is a binary file but I am having trouble distinguishing between files written in binary mode by me and files like audio, video etc files that show up as gibberish if I open them in a text editor.
How are files that show up as gibberish created? Can you please give an example of a small file that is created like this, preferably in python?
I have a feeling I am asking a really stupid question but I just had to ask it. Googling around didn't help me.
When I write to a file in binary mode (in python), I just write normal text.
You'll have to change your approach when you upgrade to Python 3.x:
>>> f = open(filename, 'wb')
>>> f.write("Hello, world!\n")
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: must be bytes or buffer, not str
>>> f.write(b"Hello, world!\n")
14
But your question isn't really about binary files. It's about str
.
In Python 2.x, str
is a byte sequence that has an overloaded meaning:
If you print the latter as it were the former, you get gibberish.
Python 3.x got rid of this double meaning by introducing a separate bytes
type for binary data, leaving str
unambiguously as a text string (and making it Unicode).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With