【问题标题】:python zipfile module with TextIOWrapper带有 TextIOWrapper 的 python zipfile 模块
【发布时间】:2011-12-13 00:30:55
【问题描述】:

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

谢谢!

【问题讨论】:

    标签: python string types zip readline


    【解决方案1】:

    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='')

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2017-04-22
      • 1970-01-01
      • 2010-10-04
      • 1970-01-01
      • 2016-01-23
      • 1970-01-01
      • 2011-05-09
      相关资源
      最近更新 更多