Search code examples
pythoncharacter-encoding

Python easy way to set default encoding for opening files in text mode?


Is there an easy and cross-platform way to set default encoding for opening files (text mode) in Python, so you don't have to write

open(filename, 'r', encoding='utf-8')

each time and can simply write

open(filename, 'r')

?


Solution

  • from io import open  # for python2 compatibility
    
    old_open = open
    def open(*args, **kwargs):
        encoding = kwargs.pop('encoding', 'utf8')
        return old_open(*args, encoding=encoding, **kwargs)