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

5
我正在使用Python编写Excl到CSV转换器。我的操作系统是Linux,Python版本为: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。
在下面的代码中,当我注释掉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)

csvFile.write('###########################################################\n\n') 结尾处的双\n是否与此有关? - 101
@figs 不好意思,我已经保留了一个“\n”,但还是不行 :-( - Riad
1个回答

18

csv.writer 的默认行终止符是 '\r\n'。如果您只想要 '\n',请显式指定lineterminator参数:

wr = csv.writer(csvFile, delimiter=';', lineterminator='\n')

我尝试了使用Python v3.5.1,但它不起作用:(,我仍然得到\r\n。为什么会这样?我的文件是以文本形式打开的。 - Ciprian Tomoiagă

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接