2

The following piece of code creates a CSV file, but every other line is blank. How can I prevent these linebreaks from happening?

import datetime
import time
import csv

i = 0
while i < 10:
    TempProbe = "78.12" 
    CurrentTime = time.strftime("%x")
    CurrentDate = time.strftime("%I:%M:%S")
    stringAll = TempProbe + "," + CurrentTime + "," + CurrentDate
    print(stringAll)
    file = open("outFile.csv", "a")
    csvWriter = csv.writer( file )
    csvWriter.writerow( [TempProbe, CurrentTime,CurrentDate] )
    file.close()
    i = i + 1
    time.sleep(1)
Alan Kavanagh
  • 9,425
  • 7
  • 41
  • 65

4 Answers4

5

This is probably because the default line terminator is '\r\n'. You can correct this by passing lineterminator='\n' to your csv.writer object, like so:

csvWriter = csv.writer(file, lineterminator='\n')

P.S. Move this line out of your while loop to avoid destroying and recreating the file writer object.

Moses Koledoye
  • 77,341
  • 8
  • 133
  • 139
  • 1
    I never understood while people are using `csv` library for saving files. Since `*.csv` files are simple text files, it's perfectly good (and faster) to just create a proper string and dump it into the file. – Laszlowaty Jun 04 '16 at 21:06
  • 1
    I find the `dictwriter` of the `csv` module very handy. Much neater than dumping into the file directly. It even gets better when you need to open a tab delimited file. – Moses Koledoye Jun 04 '16 at 21:12
1

You need to set the lineterminator for your csvWriter, as in the code below.

csvWriter = csv.writer(file, lineterminator='\n')

For an explanation why, see: CSV file written with Python has blank lines between each row

Community
  • 1
  • 1
wschella
  • 141
  • 5
0

You can simply use the open function to write a csv file:

file = open("outFile.csv", "a")
file.write(stringAll+'\n')

Also, you should take the file open and close functions out of the loop.

Ajeet Shah
  • 18,551
  • 8
  • 57
  • 87
0

Use this: 'ab' vs 'a',writes binary should fix the problem

file = open("outFile.csv", "ab")
csvWriter = csv.writer(file, lineterminator='\n' )

or this you dont need to open/close on every write :

file      = open("outFile.csv", "ab")
csvWriter = csv.writer(file, lineterminator='\n' )

i = 0
while i < 10:
    TempProbe = "78.12" 
    CurrentTime = time.strftime("%x")
    CurrentDate = time.strftime("%I:%M:%S")
    stringAll = TempProbe + "," + CurrentTime + "," + CurrentDate
    print(stringAll)
    csvWriter.writerow( [TempProbe, CurrentTime,CurrentDate] )   
    i = i + 1
    time.sleep(1)

file.close()
Merlin
  • 24,552
  • 41
  • 131
  • 206