2014-09-01 40 views
2

我正在寫一個EXCEL CSV轉換器使用python。 我在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)]在linux2上Python:write.csv添加額外的回車

在下面的代碼中,當我評論5「csvFile.write」行時,csv文件生成得很好。但是,在代碼原樣的情況下,在「wr.writerow」生成的所有行的末尾添加回車符。

問題:當「csvFile.write」存在時,爲什麼csv write會添加額外的回車符?

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) 
+0

在csvFile.write的'結束(「是否雙'\ N' ################# ########################################## \ n \ n')'have與它有關嗎? – 101 2014-09-02 00:43:36

+0

@figs不,我保留了一個「\ n」,沒有運氣:-( – Riad 2014-09-02 04:20:13

+1

[Python中添加額外的回車]的CSV的可能重複(http://stackoverflow.com/questions/3191528/csv-in- python-adding-an-extra-carriage-return) – Paul 2016-08-01 23:01:33

回答

10

csv.writer的默認行終止符是'\r\n'。明確指定,如果你只想要'\n'lineterminator說法:

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

我試過用python v3.5.1,它不起作用:(我仍然得到'\ r \ n'。爲什麼?我的文件打開作爲文本 – 2016-12-21 21:04:18

+0

@CiprianTomoiaga,像OP那樣用二進制模式打開文件'open('....','wb')' – falsetru 2016-12-22 00:14:14