pythonfrench

Python print french characters to another file


Whenever I print a french character (for example "é") in another file using python, it changes it to a weird character.

program.py:

f = open("file.txt", 'w')
print("é, è, ç", file=f)

file.txt:

�, �, �

So please does anyone know how to print out french characters to any other files as they are?


Solution

  • You can try using UTF-8 encoding:

    f = open("file.txt", 'w', encoding='utf-8')
    print("é, è, ç", file=f)
    
    # é, è, ç
    

    The default encoding is platform dependent, but any encoding supported by Python can be passed. See the codecs module for the list of supported encodings.