Python:write.csv添加额外的回车

时间:2014-09-01 22:47:39

标签: python python-2.7 csv carriage-return

我正在使用python编写一个Excl to CSV转换器。 我在Linux上运行,我的Python版本是: Python 2.7.1(r271:86832,2012年12月4日,17:16:32) [gCC 4.1.2 20080704(Red Hat 4.1.2-51)] on linux2

在下面的代码中,当我评论5“csvFile.write”行时,生成的csv文件都很好。但是,使用代码,在“wr.writerow”生成的所有行的末尾都会添加一个回车符。

问题:当“csvFile.write”存在时,为什么csv写入会添加额外的回车符?

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)

1 个答案:

答案 0 :(得分:11)

csv.writer的默认行终止符为'\r\n'。如果只需要'\n'

,请明确指定lineterminator参数
wr = csv.writer(csvFile, delimiter=';', lineterminator='\n')