Prashanth_Ramanathan Prashanth_Ramanathan - 4 months ago 8
Python Question

Remove the last empty line in CSV file

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


I'm trying to read
Input file
which is in Table Format and write it in a CSV file, but my Output contains one last empty line also. How can I remove the last empty line in CSV?

Answer

It sounds like you have an empty line in your input file. From your comments, you actually have a non-empty line that has no | characters in it. In either case, it is easy enough to check for any case that would produce an empty result line.

Try this:

#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")

Other notes:

  • You should use with consistently. Open both files the same way.
  • str(row) is a no-op. row is already a str.
  • str(','.join(...)) is similarly redundant.
  • open(..., 'read') is not a valid use of the mode parameter to open(). You should use r or even omit the parameter altogether.
  • I prefer not to introduce new names when changing the format of existing data. That is, I prefer row = row.split() over Reformatted_line = row.split().

Here is a version that incorporates these and other suggestions:

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