I am very sorry, but writing a character to a text file, not to mention that the encoding of the file should just be insensitive.
This may not be obvious at first glance, but text files are actually encoded and can be encoded in different ways. If you have only letters (upper and lower case, but not accented), numbers and simple characters (everything that has an ASCII code below 128), everything should be fine, because ASCII 7 bits are now standard, and in fact these characters have the same representation in basic encodings.
But as soon as you get true characters or accented characters, their presentation varies from one encoding to another. For example, the β character has a UTF-8 representation (Python encoding): \xe2\x97\x8f . Worse still, it cannot be represented in latin1 (ISO-8859-1) encoding.
Another example is the French accent aigu: Γ© it is represented in UTF8 as \xc3\xa9 (note 2 bytes), but represented in Latin1 as \x89 (one byte)
So, I checked your code in my Ubuntu field using UTF8 encoding and the cat myFile.txt ... correctly showed the bullet!
sba@sba-ubuntu :~/stackoverflow$ cat myFile.txt β sba@sba-ubuntu :~/stackoverflow$
(since you did not add a new line after the bullet, it immediately follows it)
Finally:
Your code correctly writes the marker to the file in UTF8 encoding. If your system uses a different encoding from the very beginning (ISO-8859-1 or its version of Windows-1252), you cannot convert it initially, because this character simply does not exist in these encodings.
But you can always see it in a text editor that supports various encodings, such as the excellent vim that exists on all major systems.
The proof above:
On a computer running Windows 7, I opened a vim window and instructed it to accept utf8 with :set encoding='utf8' . Then I pasted the source code from OP and saved it in the file foo.py
I opened the cmd.exe window and executed python foo.py (using Python 2.7): it created a myFile.txt file containing 3 bytes (hexa): e2 97 8f , which is a utf8 bullet view β (I could confirm this with vim Tools / Hexa convert).
I could even open myFile.txt in standby mode and actually saw the bullet. Even notepad.exe can show a bullet!
Thus, even on a computer running Windows 7, which initially does not accept utf-8, the code from OP correctly generates a text file that, when opened with a text editor that accepts UTF-8, contains a β marker.
Of course, if I try to open myFile.txt with vim in latin1 mode, I get: Γ’β , in cmd windows with code page 850, type myFile.txt shows ΓΓΉΓ
, and with code page 1252 (latin1 variant): Γ’ -.
In conclusion, the original OP code creates the correct utf8 encoded file - this is part of the reading to correctly interpret utf8.