Skip to content Skip to sidebar Skip to footer

Python Csv Insert Final Newline - How Can I Avoid It?

Let's say I create a csv with two lines: >>> import csv >>> csvfile = csv.writer(open('test.csv', 'w')) >>> csvfile.writerow(['row']) 5 >>> csvf

Solution 1:

As a workaround you could use a StringIO() object to write to. The output could then have rstrip() applied to it before writing to a file:

from io importStringIO        
import csv

output = StringIO(newline='')
csvfile = csv.writer(output)

csvfile.writerow(['row'])
csvfile.writerow(['row2'])        

withopen('test.csv', 'w', newline='') asf_output:
    f_output.write(output.getvalue().rstrip())

This has the benefit of preserving the full functionality of the CSV library. I would though recommend you keep the trailing newline.


For an iterative approach:

from io import StringIO        
import csv

data = [['row'], ['row2']]

withopen('test.csv', 'w', newline='') as f_output:
    iter_data = iter(data)
    next_row = next(iter_data)
    csv_writer = csv.writer(f_output)

    for row in iter_data:
        csv_writer.writerow(next_row)
        next_row = row

    # Write the last row to a string to remove trailing newline
    last_row = StringIO(newline='')
    csv.writer(last_row).writerow(next_row)
    f_output.write(last_row.getvalue().rstrip())        

This writes the data a row at a time and then deals with the last row using the StringIO() approach to remove the trailing newline.

Solution 2:

After a bit of investigation, I found the writerow source: https://hg.python.org/cpython/file/tip/Modules/_csv.c#l1254

And, from what I can guess, there is no such option in there

Solution 3:

Do this:

open('test.csv').read().strip('\n').split('\n')

Post a Comment for "Python Csv Insert Final Newline - How Can I Avoid It?"