Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How write csv file without new line character in last line?

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 in image

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.

like image 535
open source guy Avatar asked Oct 11 '13 03:10

open source guy


People also ask

How do I remove a line break in CSV?

Press and hold the Alt key and then enter “010” from your keyboard's 10-keypad part.

Should CSV end with New line?

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

What is the end of line character in CSV?

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.

How do I skip a line in CSV reader?

Use csv. reader() and next() to skip the first line of a .


Video Answer


2 Answers

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.

like image 147
falsetru Avatar answered Sep 20 '22 14:09

falsetru


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)
like image 29
arispen Avatar answered Sep 17 '22 14:09

arispen