Can I make decode (errors = "ignore") the default for all lines in a Python 2.7 program?

I have a Python 2.7 program that writes data from various external applications. I constantly bite with exceptions when I write to a file until I add .decode(errors="ignore")to the written line. (FWIW, opening a file mode="wb"does not fix this.)

Is there a way to say "ignore coding errors for all lines in this area"?

+5
source share
3 answers

You cannot override methods for built-in types, and you cannot change the default value of a parameter errorsto str.decode(). However, there are other ways to achieve the desired behavior.

: decode():

def decode(s, encoding="ascii", errors="ignore"):
    return s.decode(encoding=encoding, errors=errors)

decode(s) s.decode(), , ?

: errors, , errors="strict" :

import codecs
def strict_handler(exception):
    return u"", exception.end
codecs.register_error("strict", strict_handler)

errors="strict" "ignore". , , .

. - . ( , .)

+5

, , str :

class easystr(str):
    def decode(self):
        return str.decode(self, errors="ignore")

easystr, :

line = easystr(input.readline())

, unicode, . , , encoding decode? ( ).

, - -. , :

import codecs
input = codecs.open(filename, "r", encoding="latin-1") # or whatever
+1

, :

import codecs
codecs.register_error("strict", codecs.ignore_errors)
+1

All Articles