简体   繁体   English

Iterdecode从文件中跳过行

[英]Iterdecode skipping lines from file

When reading a .txt file from a zip and using iterdecode to read line by line, the itercode is skipping not empty odd lines. 从zip读取.txt文件并使用iterdecode逐行读取时,itercode会跳过非空的奇数行。

with zipfile.ZipFile('path/file.zip', 'r') as zipobj:
    for current_file in zipobj.namelist():
        file = zipobj.open(current_file)
        for line in codecs.iterdecode(file, 'latin-1'): #Latin-1 for accents
            print(line)

My files are .txt files and for each file: 我的文件是.txt文件,对于每个文件:

line 1
line 2
line 3
line 4
line 5, etc.

print(line) gives:

line 1
line 3
line 5, etc.

Before I was using file.open (without iterdecodes) and it worked fine, but I need to read from .zip. 在我使用file.open(没有iterdecodes)之前,它工作正常,但是我需要阅读.zip。

Thanks. 谢谢。

I solved this issue by using one of the answers from this post . 我通过使用其中一个答案解决了这个问题, 这个帖子 I will post here the solution as well as it's not so evident in the other post (not the accepted solution anyway). 我将在此处发布该解决方案,以及在其他帖子中并不太明显(无论如何都不是公认的解决方案)。

import io
with zipfile.ZipFile('path/file.zip', 'r') as zipobj:
    for name in zipobj.namelist():
        with zipobj.open(name) as readfile:
            for line in io.TextIOWrapper(readfile, 'latin-1'):
                print(line)

Now all lines are correctly printed. 现在,所有行均已正确打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM