Python:write.csv添加额外的回车 [英] Python: write.csv adding extra carriage return

查看:513
本文介绍了Python:write.csv添加额外的回车的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用python写一个Excl到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



在下面的代码中,当我注释5csvFile.write行时,csv文件生成所有精细。但是,使用代码,在wr.writerow生成的所有行的末尾添加回车符。



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

  import sys#与Unix Shell交互
import os#用于操作系统信息(主要是路径处理)

导入时间#用于数据和时间
import xlrd#用于读取XLS / XLSX文件
import csv#Writing CSV文件

#从cmd行参数获取Excel文件
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
#输出文件
csvFileName = os.path.splitext(excelFile)[0] +'.csv'
#打开写入文件
try:
csvFile = open(csvFileName,'wb')
除了IOError:
print错误:无法打开输出CSV文件
#将一个标题输出到输出文件
csvFile.write('######### ################################################## \ n')
csvFile.write('#Date:%s \\\
'%\ n')
csvFile.write('#Python Version:%s \\\
'%(sys.version) time.strftime(%d /%m /%Y,%H:%M:%S))
csvFile.write('#User:%s\\\
'%os.getlogin
csvFile.write('######################################## ###################\\################################################################################################# )

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

csvFile.close()

如果__name__ ==__main__:
csv_from_excel(excelFile)
pre>

解决方案

csv.writer 的默认行终止符为'\r\\\
'
。显式指定 lineterminator 如果只想要'\\\
'

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


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)

解决方案

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

这篇关于Python:write.csv添加额外的回车的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆