Is there a way to set encoding for all files read and written by python

I have a script in python that should read iso-8859-1 files and also write in this encoding.

Now I am running the script in an environment with all locales set to utf-8. Is there a way to define in my python scripts that all access files should use iso-8859-1 encoding?

+2


a source to share


1 answer


Python doesn't really listen to the environment when it comes to reading and writing files in a specific encoding. It only listens to the environment when it comes to unicode encoding written to stdout if stdout is connected to a terminal.

When reading and writing files in Python 2.x, you use bytes (type str

) by default . They are encoded with data. You have to decode the data you read by hand and encode what you want to write. Or you can use codecs.open()

to open files that will do the encoding for you.



In Python 3.x, you open files either in binary mode, in which case you get bytes

, or you open it in text mode, in which case you have to specify the encoding just like using codecs.open()

in Python 2.x.

None of these depend on environment variables; you are either reading bytes or specifying the encoding.

+4


a source







All Articles