Чтение utf-8 символы из gzip файла в Python

Одна вещь, которую нужно добавить - я обнаружил, что синтаксис синтаксиса Razor (и, вероятно, компилятор) интерпретирует положение открытой скобки по-разному:

<script type="text/javascript">
    var somevar = new Array();

    @foreach (var item in items)
    {  // <----  placed on a separate line, NOT WORKING, HILIGHTS SYNTAX ERRORS
        <text>
        </text>
    }

    @foreach (var item in items) {  // <----  placed on the same line, WORKING !!!
        <text>
        </text>
    }
</script>
26
задан Juan Besa 10 December 2009 в 20:16
поделиться

3 ответа

I don't see why this should be so hard.

What are you doing exactly? Please explain "eventually it reads an invalid character".

It should be as simple as:

import gzip
fp = gzip.open('foo.gz')
contents = fp.read() # contents now has the uncompressed bytes of foo.gz
fp.close()
u_str = contents.decode('utf-8') # u_str is now a unicode string

EDITED

This answer works for Python2 in Python3, please see @SeppoEnarvi 's answer at https://stackoverflow.com/a/19794943/610569 (it uses the rt mode for gzip.open.

21
ответ дан 28 November 2019 в 04:16
поделиться

Может быть

import codecs
zf = gzip.open(fname, 'rb')
reader = codecs.getreader("utf-8")
contents = reader( zf )
for line in contents:
    pass
21
ответ дан Jochen Ritzel 15 October 2019 в 07:05
поделиться

В питонической форме (2,5 или более)

from __future__ import with_statement # for 2.5, does nothing in 2.6
from gzip import open as gzopen

with gzopen('foo.gz') as gzfile:
    for line in gzfile:
      print line.decode('utf-8')
0
ответ дан Douglas Mayle 15 October 2019 в 07:05
поделиться
Другие вопросы по тегам:

Похожие вопросы: