带有 TextIOWrapper 的 python zipfile 模块

Lan*_*ins 6 python string zip types readline

我编写了以下代码来读取压缩目录中的文本文件。由于我不想以字节为单位输出,因此我添加了 TextIOWrapper 以将输出显示为字符串。假设这是逐行读取 zip 文件的正确方法(如果不让我知道),那么为什么输出会打印一个空行?有没有办法摆脱它?

import zipfile
import io

def test():
    zf = zipfile.ZipFile(r'C:\Users\test\Desktop\zip1.zip')
    for filename in zf.namelist():
        words = io.TextIOWrapper(zf.open(filename, 'r'))
        for line in words:
            print (line)
    zf.close()

test()

>>> 
This is a test line...

This is a test line...
>>> 

The two lines in the file inside of the zipped folder are:
This is a test line...
This is a test line...
Run Code Online (Sandbox Code Playgroud)

谢谢!

Ery*_*Sun 5

zipfile.open以二进制模式打开压缩文件,它不会删除回车符(即“\r”),并且TextIOWrapper在我的测试中也没有默认值。尝试配置TextIOWrapper使用通用换行符(即newline=None):

import zipfile
import io

zf = zipfile.ZipFile('data/test_zip.zip')
for filename in zf.namelist():
    with zf.open(filename, 'r') as f:
        words = io.TextIOWrapper(f, newline=None)
        for line in words:
            print(repr(line))
Run Code Online (Sandbox Code Playgroud)

输出:

'This is a test line...\n'
'This is a test line...'
Run Code Online (Sandbox Code Playgroud)

在 Python 中逐行迭代文件时的正常行为是在末尾保留换行符。该print函数还添加了一个换行符,因此您将得到一个空行。要打印文件,您可以改为使用print(words.read()). 或者您可以使用end打印功能的选项:print(line, end='')