How to accent in Python


I'm writing a program and it gets giving ascii error. I've already put this on the first line and nothing:

# -*- coding: utf-8 -*-  

On request, it follows edition explaining what is now.

now it is variable for datetime and I believe it has no relation.

The accent on the console (terminal) is normal. What does not work is because I put it to write in a .txt file and when put to write with accent it appears that error.

I did what mgibsonbr asked and gave it all ok. I use OS X.

So, recapping:
- now is a variable for datetime that has nothing with accentuation (I believe);
- The accent error only appears when writing to a .txt file;

asked by anonymous 20.05.2015 / 01:43

1 answer


When you open a file in Python for writing using built-in open :

with open("arquivo.txt", mode="w") as f:

It assumes that this file is in the system default encoding (in Python 2, it assumes the file is latin-1 , which is very bad). Or at least that's what the documentation says, because its error suggests that the stream is rejecting characters above 0x7F , so the encoding used seems to be ASCII.

Python 3 has some different methods of dealing with character encodings , but the most recommended way to work with text files when you have full control over them is to provide explicit encoding. So writing should go smoothly:

with open("arquivo.txt", mode="w", encoding="utf-8") as f:

For reference, I'll also show you how to do it in Python 2:

import codecs
with"arquivo.txt", "w", "utf-8") as f:

Of course, you can choose another character encoding for your output file if you want (it does not have to be the same as the source file).

20.05.2015 / 05:27