删除CSV fi中的最后一个空行

2024-10-02 00:31:25 发布

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

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中的最后一个空行?在


Tags: csvreadinputoutputaswithlineopen
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)

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

试试这个:

#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)是no-op。row已经是str
  • str(','.join(...))同样是冗余的。在
  • open(..., 'read')不是open()的模式参数的有效使用。您应该使用r,甚至完全忽略该参数。在
  • 我不希望在更改现有数据格式时引入新名称。也就是说,我更喜欢row = row.split(),而不是{}。在

以下是一个包含以下建议和其他建议的版本:

^{pr2}$

相关问题 更多 >

    热门问题