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)
1
  • 2
    Works perfect for me as it is on 2.7 Commented Jun 4, 2016 at 20:58

4 Answers 4

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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

Comments

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.

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.