python在写入fi时在第一行打印空行

2024-05-23 07:55:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我不明白为什么我的代码在向文件写入文本之前要打印一个空行。我正在做的是从一个压缩文件夹中读取两个文件,并将文本写入一个新的文本文件。我在文件中得到了预期的结果,除了文件的第一行有一个空行。

def test():
    if zipfile.is_zipfile(r'C:\Users\test\Desktop\Zip_file.zip'):
        zf = zipfile.ZipFile(r'C:\Users\test\Desktop\Zip_file.zip')
        for filename in zf.namelist():
            with zf.open(filename, 'r') as f:
                words = io.TextIOWrapper(f)
                new_file = io.open(r'C:\Users\test\Desktop\new_file.txt', 'a')
                for line in words:
                    new_file.write(line)
                new_file.write('\n')
    else:
        pass

    zf.close()
    words.close()
    f.close()
    new_file.close()

在新的_文件中输出(在第一个“这是测试行…”之前有一个空行)

This is a test line...
This is a test line...
this is test #2
this is test #2

有什么想法吗?

谢谢!


Tags: 文件test文本newcloseislinezip
1条回答
网友
1楼 · 发布于 2024-05-23 07:55:53

我的猜测是zf.namelist()中的第一个文件不包含任何内容,因此跳过该文件的for line in words循环,只需执行new_file.write('\n')。如果看不到正在循环的文件,很难分辨;也许可以添加一些调试语句,打印出文件名和一些信息,例如文件大小。

相关问题 更多 >

    热门问题