Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why does Python 3 read a file with encoding cp1252 by default?

When doing:

with open('test.txt', 'r') as f:
    print(f)

I get:

<_io.TextIOWrapper name='test.txt' mode='r' encoding='cp1252'>

Why is it cp1252 by default? The test.txt has been saved with UTF8 encoding, and the .py script too.

like image 969
Basj Avatar asked Jul 24 '26 20:07

Basj


1 Answers

Directly from the documentation of open:

The default encoding is platform dependent (whatever locale.getpreferredencoding() returns), but any text encoding supported by Python can be used. See the codecs module for the list of supported encodings.

My bolding

If you want to read as UTF-8 you just use the argument:

with open('test.txt', 'r', encoding='utf-8') as f:
    print(f)
like image 90
Artog Avatar answered Jul 26 '26 11:07

Artog



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!