I have a code like this to write csv file in python
import csv
with open('eggs.csv', 'wb') as csvfile:spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
output shown in in image.
Now there is an extra line in output (line 3). How can i remove this last empty line while writing csv file.
Use file.seek
to move file pointer before the last \r\n
, then use file.truncate
.
import os
import csvwith open('eggs.csv', 'wb') as csvfile:spamwriter = csv.writer(csvfile, delimiter=' ',quotechar='|', quoting=csv.QUOTE_MINIMAL)spamwriter.writerow(['Spam'] * 5 + ['Baked Beans'])spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])csvfile.seek(-2, os.SEEK_END) # <---- 2 : len('\r\n')csvfile.truncate() # <----
NOTE: You should change -2
if you use different lineterminator
. I used -2
because \r\n
is default lineterminator.