Rather than mess with .encode and .decode, specify the encoding when opening the file. The io module, added in Python 2.6, provides an io.open function, which allows specifying the file's encoding.

Supposing the file is encoded in UTF-8, we can use:

>>> import io
>>> f = io.open("test", mode="r", encoding="utf-8")

Then f.read returns a decoded Unicode object:

>>> f.read()
u'Capit\xe1l\n\n'

In 3.x, the io.open function is an alias for the built-in open function, which supports the encoding argument (it does not in 2.x).

We can also use open from the codecs standard library module:

>>> import codecs
>>> f = codecs.open("test", "r", "utf-8")
>>> f.read()
u'Capit\xe1l\n\n'

Note, however, that this can cause problems when mixing read() and readline().

Answer from Tim Swena on Stack Overflow
Top answer
1 of 14
914

Rather than mess with .encode and .decode, specify the encoding when opening the file. The io module, added in Python 2.6, provides an io.open function, which allows specifying the file's encoding.

Supposing the file is encoded in UTF-8, we can use:

>>> import io
>>> f = io.open("test", mode="r", encoding="utf-8")

Then f.read returns a decoded Unicode object:

>>> f.read()
u'Capit\xe1l\n\n'

In 3.x, the io.open function is an alias for the built-in open function, which supports the encoding argument (it does not in 2.x).

We can also use open from the codecs standard library module:

>>> import codecs
>>> f = codecs.open("test", "r", "utf-8")
>>> f.read()
u'Capit\xe1l\n\n'

Note, however, that this can cause problems when mixing read() and readline().

2 of 14
126

In the notation u'Capit\xe1n\n' (should be just 'Capit\xe1n\n' in 3.x, and must be in 3.0 and 3.1), the \xe1 represents just one character. \x is an escape sequence, indicating that e1 is in hexadecimal.

Writing Capit\xc3\xa1n into the file in a text editor means that it actually contains \xc3\xa1. Those are 8 bytes and the code reads them all. We can see this by displaying the result:

# Python 3.x - reading the file as bytes rather than text,
# to ensure we see the raw data
>>> open('f2', 'rb').read()
b'Capit\\xc3\\xa1n\n'

# Python 2.x
>>> open('f2').read()
'Capit\\xc3\\xa1n\n'

Instead, just input characters like á in the editor, which should then handle the conversion to UTF-8 and save it.

In 2.x, a string that actually contains these backslash-escape sequences can be decoded using the string_escape codec:

# Python 2.x
>>> print 'Capit\\xc3\\xa1n\n'.decode('string_escape')
Capitán

The result is a str that is encoded in UTF-8 where the accented character is represented by the two bytes that were written \\xc3\\xa1 in the original string. To get a unicode result, decode again with UTF-8.

In 3.x, the string_escape codec is replaced with unicode_escape, and it is strictly enforced that we can only encode from a str to bytes, and decode from bytes to str. unicode_escape needs to start with a bytes in order to process the escape sequences (the other way around, it adds them); and then it will treat the resulting \xc3 and \xa1 as character escapes rather than byte escapes. As a result, we have to do a bit more work:

# Python 3.x
>>> 'Capit\\xc3\\xa1n\n'.encode('ascii').decode('unicode_escape').encode('latin-1').decode('utf-8')
'Capitán\n'
Discussions

Backporting Python 3 open(encoding="utf-8") to Python 2 - Stack Overflow
Now I'd like to backport this code to Python 2.x, so that I would have a codebase which works with Python 2 and Python 3. What's the recommended strategy to work around open() differences and lack of encoding parameter? More on stackoverflow.com
🌐 stackoverflow.com
open(encoding="utf-8") の使い方
Python学習に関するあらゆるトピックについて質問を投稿したり、一般的なアドバイスを求めたりするためのサブredditです。 ... ファイルを扱うときに、たまにUnicodeDecodeErrorに遭遇するんだよね。どうやら、すべてのUnicode文字が文字列に変換できるわけじゃないらしくて、encoding="utf-8... More on reddit.com
🌐 r/learnpython
16
3
November 2, 2020
The use of open(encoding="utf-8")
open defaults to whatever encoding your system uses by default, so it can be anything from ASCII to ISO-8859-1. You can, however, make it use a specific encoding instead. utf-8 is useful as it has most characters. More on reddit.com
🌐 r/learnpython
16
3
November 2, 2020
Debate: Enforcing Python source encoding as UTF-8
However, I recently was told that forcing the source encoding to UTF-8 can be bad for cross-platform compatibility, since Windows doesn't default to UTF-8. First of all, as far as source files go, Windows doesn't default to anything, programs do. Notepad in Windows-7 defaults to UTF-8, if your code editor is worse than Notepad then you probably should get another code editor. Maybe the person who told you that was thinking about encoding of stuff like file names in syscalls? I'm not sure what's supposed to be the alternative approach then. If you use ASCII encoding for source files and manually encode Unicode characters with backslash escapes in bytestrings you still has to decide how to encode them, in UTF-8 or UCS-2 that Windows expects. And the correct way is, of course, to just use unicode literals instead. Also, you can't "not enforce" the source encoding, if you don't specify UTF-8 then it's 7-bit ASCII. Which is good, because I can't imagine how an unspecified source encoding can be good for cross-platform compatibility -- if someone runs your script on Windows and Python there somehow decided to use UTF-16, they get garbage printed out? More on reddit.com
🌐 r/Python
23
7
July 31, 2014
🌐
Python documentation
docs.python.org › 3 › howto › unicode.html
Unicode HOWTO — Python 3.14.7 documentation
The default encoding for Python source code is UTF-8, so you can simply include a Unicode character in a string literal: try: with open('/tmp/input.txt', 'r') as f: ... except OSError: # 'File not found' error message.
🌐
Python
docs.python.org › 3 › library › codecs.html
codecs — Codec registry and base classes
Unicode characters are encoded like this (with x being payload bits, which when concatenated give the Unicode character): The least significant bit of the Unicode character is the rightmost x bit. As UTF-8 is an 8-bit encoding no BOM is required and ...
🌐
Honeybadger
honeybadger.io › blog › python-character-encoding
Python developer's guide to character encoding - Honeybadger Developer Blog
March 6, 2023 - There is also a UnicodeDecodeError, which occurs when the character encoding of the bytes we are reading and the character encoding Python is attempting to use to read them are not similar. ... One way to fix a character encoding error is to use the ignore or replace method to remove special characters or emojis that cannot be encoded. You can also use the ignore method when opening a file to avoid any errors. Here is an example: text = 'ф' with open('message.txt', 'w', encoding='utf-8', errors='ignore') as f: f.write(text)
🌐
Python Morsels
pythonmorsels.com › unicode-character-encodings-in-python
Unicode character encodings - Python Morsels
May 2, 2022 - But on Windows, the default character encoding is usually cp1252. Note: Since Python 3.6, all files are read and written by Python using utf-8 by default, even on Windows.
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › article › how-to-read-and-write-unicode-utf-8-files-in-python
How to read and write unicode (UTF-8) files in Python?
# Create a sample UTF-8 file first with open('sample.txt', 'w', encoding='utf-8') as f: f.write('Hello World! ???? ?') # Read the UTF-8 file with open('sample.txt', 'r', encoding='utf-8') as f: content = f.read() print(content) ...
🌐
Curiousefficiency
python-notes.curiousefficiency.org › en › latest › python3 › text_file_processing.html
Processing Text Files in Python 3 - Alyssa Coghlan's Python Notes
Example: f = tokenize.open(fname) uses PEP 263 encoding markers to detect the encoding of Python source files (defaulting to UTF-8 if no encoding marker is detected)
🌐
YouTube
youtube.com › fewsteps
Opening files in Python - open('file.txt', mode='wt', encoding='utf-8') - YouTube
This video explains how to change Date and Time in Windows 10 Python Encoding Lists: https://docs.python.org/3/library/codecs.html#standard-encodings ♥️ Subs...
Published: April 14, 2020
Views: 484
🌐
Stanford
web.stanford.edu › class › archive › cs › cs106a › cs106a.1204 › handouts › py-file.html
Python File Reading
The form open(filename, encoding='utf-8') can specify the encoding to use to interpret the text file as unicode. If reading a file crashes with a "UnicodeDecodeError", probably the reading code needs to specify an encoding as above. Try the 'utf-8' encoding first, as many files are encoded with it.
🌐
LabEx
labex.io › tutorials › python-how-to-use-python-utf8-encoding-451217
How to use Python UTF8 encoding | LabEx
Encoding and decoding are fundamental processes for converting text between different representations in Python. ## String to bytes encoding text = "Hello, 世界!" encoded_text = text.encode('utf-8') print(encoded_text) ## Converts string to UTF-8 bytes ## Bytes to string decoding decoded_text = encoded_text.decode('utf-8') print(decoded_text) ## Converts bytes back to string
🌐
Real Python
realpython.com › python-encodings-guide
Unicode & Character Encodings in Python: A Painless Guide – Real Python
May 20, 2019 - Note: If you type help(str.encode), you’ll probably see a default of encoding='utf-8'. Be careful about excluding this and just using "résumé".encode(), because the default may be different in Windows prior to Python 3.6.
🌐
SSOJet
ssojet.com › character-encoding-decoding › utf-8-in-python
UTF-8 in Python | Encoding Standards for Programming Languages
When working with text files in Python, explicitly specifying the encoding='utf-8' parameter in the open() function is crucial for accurate character handling.
🌐
University of Pittsburgh
sites.pitt.edu › ~naraehan › python3 › reading_writing_methods.html
Python 3 Notes: Reading and Writing Methods
Python 3 Notes [ HOME | LING 1330/2330 ] File Reading and Writing Methods << Previous Note Next Note >> On this page: open(), file.read(), file.readlines(), file.write(), file.writelines(), with open() as f:. Before proceeding, make sure you understand the concepts of file path and CWD.
🌐
Python
peps.python.org › pep-0686
PEP 686 – Make UTF-8 mode default | peps.python.org
March 18, 2022 - Inconsistent default encoding causes many bugs. Python will enable UTF-8 mode by default from Python 3.15.
🌐
Python Forum
python-forum.io › thread-42020.html
[SOLVED] Right way to open files with different encodings?
April 23, 2024 - Hello, Some of the files could be Windows (latin1, iso9959-1, cp1252), others could be utf-8. Is try/except the right way to do it? #with open(file, 'r') as f: #with open(file, 'r',encoding='utf-8') as f: #latin1, iso9959-1, cp1252 with open(file,...
🌐
Python Module of the Week
pymotw.com › 2 › codecs
codecs – String encoding and decoding - Python Module of the Week
EncodedFile() takes an open file handle using one encoding and wraps it with a class that translates the data to another encoding as the I/O occurs. from codecs_to_hex import to_hex import codecs from cStringIO import StringIO # Raw version of the original data. data = u'pi: \u03c0' # Manually ...
🌐
LabEx
labex.io › tutorials › python-how-to-handle-python-file-text-encoding-421209
How to handle Python file text encoding | LabEx
Python provides multiple methods to read files with specific encodings: ## Reading a text file with UTF-8 encoding with open('example.txt', 'r', encoding='utf-8') as file: content = file.read() print(content) For large files, use iterative reading ...