8
votes

[Using Python 3.2]

If I don't provide encoding argument to open, the file is opened using locale.getpreferredencoding(). So for example, on my Windows machine, any time I use open('abc.txt'), it would be decoded using cp1252.

I would like to switch all my input files to utf-8. Obviously, I can add encoding = 'utf-8' to all my open function calls. Or, better, encoding = MY_PROJECT_DEFAULT_ENCODING, where the constant is defined at the global level somewhere.

But I was wondering if there is a clean way to avoid editing all my open calls, by changing the "default" encoding. Is it something I can change by changing the locale? Or by changing a parameter inside the locale? I tried to follow the Python manual but failed to understand how this is supposed to be used.

Thanks!

1
Before I found this question, I've asked a differently worded duplicate and received some answers. You may find them useful: Is there a way to change Python's open() default text encoding? - user
There're some more answers in the similar question: Changing the “locale preferred encoding” in Python 3 in Windows - Antony Hatchkins
See stackoverflow.com/a/61570285/7796217 for a solution which I got working on Python 3.7. - Peter Fogh
See stackoverflow.com/a/61570285/7796217 for a solution I got working on Python 3.7 - Peter Fogh

1 Answers

3
votes

In Windows, with Python 3.3+, execute chcp 65001 in the console or a batch file before running Python in order to change the locale encoding to UTF-8.