繁体   English   中英

带有TextIOWrapper的python zipfile模块

[英]python zipfile module with TextIOWrapper

我编写了以下代码来读取压缩目录中的文本文件。 由于我不希望输出以字节为单位,因此我添加了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...

谢谢!

zipfile.open以二进制模式打开压缩文件,它不会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))

输出:

'This is a test line...\n'
'This is a test line...'

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

暂无
暂无

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

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