Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Read a unicode file in python which declares its encoding in the same way as python source

Tags:

python

unicode

I wish to write a python program which reads files containing unicode text. These files are normally encoded with UTF-8, but might not be; if they aren't, the alternate encoding will be explicitly declared at the beginning of the file. More precisely, it will be declared using exactly the same rules as Python itself uses to allow Python source code to have an explicitly declared encoding (as in PEP 0263, see https://www.python.org/dev/peps/pep-0263/ for more details). Just to be clear, the files being processed are not actually python source, but they do declare their encodings (when not in UTF-8) using the same rules.

If one knows the encoding of a file before one opens it, Python provides a very easy way to read the file with automatic decoding: the codecs.open command; for instance, one might do:

import codecs
f = codecs.open('unicode.rst', encoding='utf-8')
for line in f:
    print repr(line)

and each line we get in the loop will be a unicode string. Is there a Python library which does a similar thing, but choosing the encoding according to the rules above (which are Python 3.0's rules, I think)? (e.g. does Python expose the 'read file with self-declared encoding' it uses to read source to the language?) If not, what's the easiest way to achieve the desired effect?

One thought is to open the file using the usual open, read the first two lines, interpret them as UTF-8, look for a coding declaration using the regexp in the PEP, and if one finds one start decoding all subsequent lines using the encoding declared. For this to be sure to work, we need to know that for all the encodings that Python allows in Python source, the usual Python readline will correctly split the file into lines - that is, we need to know that for all the encodings Python allows in Python source, the byte string '\n' always really mean newline, and isn't part of some multi-byte sequence encoding another character. (In fact I also need to worry about '\r\n' as well.) Does anyone know if this is true? The docs were not very specific.

Another thought is to look in the Python sources. Does anyone know where in the Python source the source-code-encoding-processing is done?

like image 649
circular-ruin Avatar asked May 21 '11 00:05

circular-ruin


1 Answers

There is support for this in the standard library, even in Python 2. Here is code you can use:

try:

    # Python 3
    from tokenize import open as open_with_encoding_check

except ImportError:

    # Python 2
    from lib2to3.pgen2.tokenize import detect_encoding
    import io


    def open_with_encoding_check(filename):
        """Open a file in read only mode using the encoding detected by
        detect_encoding().
        """
        fp = io.open(filename, 'rb')
        try:
            encoding, lines = detect_encoding(fp.readline)
            fp.seek(0)
            text = io.TextIOWrapper(fp, encoding, line_buffering=True)
            text.mode = 'r'
            return text
        except:
            fp.close()
            raise

Then personally I needed to parse and compile this source. In Python 2 it's an error to compile unicode text that includes an encoding declaration, so lines containing the declaration have to be made blank (not removed, as this changes line numbers) first. So I also made this function:

def read_source_file(filename):
    from lib2to3.pgen2.tokenize import cookie_re

    with open_with_encoding_check(filename) as f:
        return ''.join([
            '\n' if i < 2 and cookie_re.match(line)
            else line
            for i, line in enumerate(f)
        ])

I'm using these in my package, the latest source (in case I find I need to change them) can be found here, while tests are here.

like image 140
Alex Hall Avatar answered Oct 21 '22 20:10

Alex Hall