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)
AK47
  • 8,646
  • 6
  • 37
  • 61

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
  • 74,909
  • 8
  • 119
  • 129
  • 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
  • 41
  • 2
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
  • 15,652
  • 7
  • 55
  • 72
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
  • 22,195
  • 35
  • 117
  • 197