【问题标题】:python printing a blank line on the first line when writing to a filepython在写入文件时在第一行打印一个空行
【发布时间】:2011-12-13 05:12:11
【问题描述】:

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

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()

new_file 中的输出(在第一个“This is a test line...”之前有一个空行)

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

有什么想法吗?

谢谢!

【问题讨论】:

    标签: python file newline


    【解决方案1】:

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

    【讨论】:

    • 我认为你是对的。当我调用 zf.namelist() 时,我得到以下列表。 ['新文件夹/','新文件夹/test1.txt','新文件夹/test2.txt']。新文件夹是保存文件的文件夹的名称。我将返回文档,看看是否有解决此问题的好方法。
    猜你喜欢
    • 2013-04-30
    • 1970-01-01
    • 1970-01-01
    • 2015-04-29
    • 2017-04-24
    • 2014-10-03
    • 2014-01-14
    • 1970-01-01
    • 2014-10-10
    相关资源
    最近更新 更多