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.
Press and hold the Alt key and then enter “010” from your keyboard's 10-keypad part.
CSV is a delimited data format that has fields/columns separated by the comma character and records/rows terminated by newlines. A CSV file does not require a specific character encoding, byte order, or line terminator format (some software do not support all line-end variations).
The files are easily editable using common spreadsheet applications like Microsoft Excel. Fields are separated by commas. Records are separated with system end of line characters, CRLF (ASCII 13 Dec or 0D Hex and ASCII 10 Dec or 0A Hex respectively) for Windows, LF for Unix, and CR for Mac.
Use csv. reader() and next() to skip the first line of a .
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)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With