How to open an unicode text file inside a zip?

后端 未结 3 1709
不知归路
不知归路 2020-12-19 06:04

I tried

with zipfile.ZipFile(\"5.csv.zip\", \"r\") as zfile:
    for name in zfile.namelist():
        with zfile.open(name, \'rU\') as readFile:
                    


        
3条回答
  •  粉色の甜心
    2020-12-19 06:36

    To convert a byte stream into Unicode stream, you could use io.TextIOWrapper():

    encoding = 'utf-8'
    with zipfile.ZipFile("5.csv.zip") as zfile:
        for name in zfile.namelist():
            with zfile.open(name) as readfile:
                for line in io.TextIOWrapper(readfile, encoding):
                    print(repr(line))
    

    Note: TextIOWrapper() uses universal newline mode by default. rU mode in zfile.open() is deprecated since version 3.4.

    It avoids issues with multibyte encodings described in @Peter DeGlopper's answer.

提交回复
热议问题