【问题标题】:Python CSV Writer leave a empty line at the end of the filePython CSV Writer 在文件末尾留一个空行
【发布时间】:2015-06-02 20:13:59
【问题描述】:

以下代码在 txt 文件的末尾留下一个空白行。我怎么能不让作者不终止最后一行?

        with open(fname, 'wb') as myFile:
        # Start the CSV Writer
        wr = csv.writer(myFile, delimiter=',', dialect='excel')
        wr.writerows(rows)

        # Close the file.
        myFile.close()

【问题讨论】:

  • 您确实意识到没有添加实际的空行?打开文件阅读并执行for line in myFile:print(repr(line)),您将看不到任何空行。
  • Padraic,您可能使用的是 Unix 系统。在 Unix 中没有添加行,在 Windows 中有。似乎不一致。

标签: python csv writer


【解决方案1】:

我找不到适用于 python 3 的答案,也适用于我的情况,所以这是我的解决方案:

def remove_last_line_from_csv(filename):
    with open(filename) as myFile:
        lines = myFile.readlines()
        last_line = lines[len(lines)-1]
        lines[len(lines)-1] = last_line.rstrip()
    with open(filename, 'w') as myFile:    
        myFile.writelines(lines)

【讨论】:

    【解决方案2】:

    首先,由于您使用的是with open as myFile,因此不需要myFile.close(),当您删除缩进时会自动完成。

    其次,如果您愿意在程序中添加另一部分,您可以简单地编写一些内容来删除最后一行。 Strawberry 做了一个例子(略有改动):

    with open(fname) as myFile:
        lines = myFile.readlines()
    with open(fname, "w") as myFile:
        myFile.writelines([item for item in lines[:-1]])
    

    注意 'w' 参数是如何清除文件的,所以我们需要打开文件两次,一次读取,一次写入。

    我也相信,您可以使用myFile.write,它不会添加换行符。使用它的一个例子是:

    with open(fname, 'wb') as myFile:
        wr = csv.writer(myFile, delimiter=',', dialect='excel')
        lines = []
        for items in rows:
            lines.append(','.join(items))
        wr.write('\n'.join(lines))
    

    这只有在你有一个多维数组时才有效,应该避免。

    【讨论】:

    • csv.writer 没有写入方法,如果行包含整数等。连接将失败。如果您只使用原始代码,所有示例的输出也将相同。
    【解决方案3】:

    感谢wfgeo,其中一个解决方案就是这样工作的。虽然它需要 os 库,但它让生活更轻松:

    import csv
    import os
    
    with open(fileName, 'w', newline='') as f:
      writer = csv.writer(f, delimiter=';', dialect='excel')
      
      for row in rows:
        row = rows[0].values()
        writer.writerow(row)
    
      f.seek(0, os.SEEK_END)
      f.seek(f.tell()-2, os.SEEK_SET)
      f.truncate()
    

    【讨论】:

      【解决方案4】:

      我很欣赏这是一个旧请求,但我在寻找相同的解决方案时偶然发现了它。我最终在 the csv documentation itself 中阅读了答案,发现 csv.writer 有一个 lineterminator 格式化参数,默认为 \r\n,给出了我们都不想要的新行。

      作为一种解决方案,我在代码中添加了格式化参数newline='',它运行良好(在下面原位)。

          with open(fname, 'wb') as myFile:
              # Start the CSV Writer
              wr = csv.writer(myFile, delimiter=',', dialect='excel', lineterminator='')
              wr.writerows(rows)
      

      【讨论】:

        猜你喜欢
        • 2012-07-26
        • 2017-01-07
        • 1970-01-01
        • 2018-07-02
        • 2013-10-16
        • 1970-01-01
        • 2021-09-27
        • 1970-01-01
        • 2022-01-07
        相关资源
        最近更新 更多