How write csv file without new line character in last line?
Use file.seek
to move file pointer before the last \r\n
, then use file.truncate
.
import os
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'])
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.
here is a solution that removes the newline symbols from last line of csv, using rstrip:
def remove_last_line_from_csv(filename):
with open(filename) as myFile:
lines = myFile.readlines()
last_line = lines[len(lines)-1]
lines[len(lines)-1] = last_line.rstrip()
with open(filename, 'w') as myFile:
myFile.writelines(lines)