pythonpython-3.xcharacter-encodingfile-encodings

Formatted output to file (write())


I am facing problem when I try to write information to the file using .format().

I am trying to write() text that has been read from text file to another file and then write information about every line:

def Spausdinti_Faile(duom, tarpai_kiek, simboliai_kiek):
    with open("rez.txt", "w") as fout:

        i = 0
        for i in range(len(duom)):
            fout.write(duom[i])

        print(tarpai_kiek, simboliai_kiek)
        i = 0
        for i in range(len(duom)):
            fout.write("{0} eilutė turi {1} tarpų simbolių ir {2} 
            simbolių.".format(str(i + 1), str(tarpai_kiek[i]), 
            str(simboliai_kiek[i])))

I get this error:

enter image description here


Solution

  • Since you're on Windows, the default character encoding for files is... something limited.

    Some of the characters in your language can't be represented in that character encoding, so you get an error to that effect.

    Open the file with the UTF-8 encoding; it can represent any character:

    with open("rez.txt", "w", encoding="UTF-8") as fout:
    

    You can also set the PYTHONUTF8=1 environment variable to have Python default to UTF-8 on Windows -- it's already the default on other platforms.