【问题标题】:Remove the last empty line in CSV file删除 CSV 文件中的最后一个空行
【发布时间】:2016-08-09 18:22:20
【问题描述】:
nf=open(Output_File,'w+')
with open(Input_File,'read') as f:
    for row in f:
        Current_line = str(row)
        Reformated_line=str(','.join(Current_line.split('|')[1:-1]))
        nf.write(Reformated_line+ "\n")

我正在尝试读取表格格式的Input file 并将其写入 CSV 文件,但我的输出还包含最后一个空行。如何删除 CSV 中的最后一个空行?

【问题讨论】:

  • 旁白:您使用with 打开一个文件而不打开另一个文件有什么原因吗?另外,你为什么打电话给str(row)?由于row 已经是str,这似乎没有任何用处。

标签: python csv


【解决方案1】:

听起来您的输入文件中有一个空行。从您的 cmets 中,您实际上有一个非空行,其中没有 | 字符。无论哪种情况,都可以很容易地检查结果是否为空。

试试这个:

#UNTESTED
nf=open(Output_File,'w+')
with open(Input_File,'read') as f:
    for row in f:
        Current_line = str(row)
        Reformated_line=str(','.join(Current_line.split('|')[1:-1]))
        if Reformatted_line:
            nf.write(Reformated_line+ "\n")

其他说明:

  • 您应该始终使用with。以相同的方式打开这两个文件。
  • str(row) 是无操作的。 row 已经是一个字符串了。
  • str(','.join(...)) 同样是多余的。
  • open(..., 'read')open() 的模式参数无效。您应该使用r,甚至完全省略该参数。
  • 我不希望在更改现有数据的格式时引入新名称。也就是说,比起Reformatted_line = row.split(),我更喜欢row = row.split()

这是一个包含这些和其他建议的版本:

with open(Input_File) as inf, open(Output_File, 'w+') as outf:
    for row in inf:
        row = ','.join(row.split('|')[1:-1])
        if row:
            outf.write(row + "\n")

【讨论】:

  • 谢谢罗伯。我是 Python 新手。我根据您的建议更改了脚本。但我仍然在 Output 中得到空行。我的 Input 中没有空行。但下面是我在 Input 中的最后一行的样子:---------------
  • 我上面的第二个例子应该在你的输入上正常工作。如果没有,请编辑您的问题以包含一个简短的完整示例程序来演示该问题。如果需要,包括样本输入。请参阅minimal reproducible example 了解更多信息。
  • @Prashanth_Ramanathan - 我已经更新了我的第一个示例来处理您描述的输入。
【解决方案2】:

只是一个重新排序的问题:

first = True
with open(Input_File,'read') as f, open(Output_File,'w+') as nf:
    for row in f:
        Current_line = str(row)
        Reformated_line=str(','.join(Current_line.split('|')[1:-1]))
        if not first:
            nf.write('\n')
        else:
            first = False
        nf.write(Reformated_line)

【讨论】:

  • 您可以在单个with 语句中open 多个文件。否则别忘了关闭nf
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2021-11-22
  • 1970-01-01
  • 1970-01-01
  • 2018-12-29
  • 1970-01-01
  • 1970-01-01
  • 2015-07-04
相关资源
最近更新 更多