Stack Overflow is a community of 4.7 million programmers, just like you, helping each other.

Join them; it only takes a minute:

Sign up
Join the Stack Overflow community to:
  1. Ask programming questions
  2. Answer and help your peers
  3. Get recognized for your expertise

I am writing an Excl to CSV converter using python. I'm running in Linux and my Python version is: Python 2.7.1 (r271:86832, Dec 4 2012, 17:16:32) [GCC 4.1.2 20080704 (Red Hat 4.1.2-51)] on linux2

In the code as below, when I comment the 5 "csvFile.write" lines, the csv file is generated all fine. However, with the code as is, a carriage return is getting added at the end of all the lines produced by "wr.writerow".

Question: Why the csv write is adding the extra carriage return when "csvFile.write" are present ?

import sys  # For interacting with the Unix Shell
import os   # For OS information (mainly path manipulation)

import time # For data and time
import xlrd # For reading both XLS/XLSX files
import csv  # Writing CSV files

# Get the Excel file from cmd line arguments
excelFile = sys.argv[1]

def csv_from_excel(excelFile):
  wb = xlrd.open_workbook(excelFile, encoding_override='utf8')
  sh = wb.sheet_by_index(0)
  print sh.name, sh.nrows, sh.ncols
  # Output file
  csvFileName= os.path.splitext(excelFile)[0] + '.csv'  
  # Open file for write
  try:
    csvFile = open(csvFileName, 'wb')
  except IOError:
    print "Error: cannot open output CSV file"
  # Print a header to the output file
  csvFile.write('###########################################################\n')
  csvFile.write('# Python Version: %s\n' % (sys.version))
  csvFile.write('# Date: %s\n' % time.strftime("%d/%m/%Y, %H:%M:%S"))
  csvFile.write('# User: %s\n' % os.getlogin())
  csvFile.write('###########################################################\n\n')
  # Wite Values
  wr = csv.writer(csvFile, delimiter=';')

  for rownum in xrange(sh.nrows):
    wr.writerow([unicode(val).encode('utf8') for val in sh.row_values(rownum)])

  csvFile.close()

if __name__ == "__main__":
  csv_from_excel(excelFile)
share|improve this question
    
Does the double \n at the end of csvFile.write('###########################################################\n\n'‌​) have something to do with it? – 101 Sep 2 '14 at 0:43
    
@figs Nope, I have kept one "\n", no luck :-( – Riad Sep 2 '14 at 4:20
up vote 6 down vote accepted

Default line terminator for csv.writer is '\r\n'. Explicitly specify lineterminator argument if you want only '\n':

wr = csv.writer(csvFile, delimiter=';', lineterminator='\n')
share|improve this answer

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

Not the answer you're looking for? Browse other questions tagged or ask your own question.