Search code examples
pythoncsvxlrd

go back one character during csv write


I'm trying to convert xls sheets to CSV files.

workbook1 = xlrd.open_workbook(path+'diseaseData.xls')
for sheet in workbook1.sheet_names():
    sh = workbook1.sheet_by_name(sheet)
    csvFile = open('//....../disease-'+sheet+'.csv', 'w')
    wr = csv.writer(csvFile, quoting=csv.QUOTE_ALL)
    for rownum in range(sh.nrows):
        # print (sh.row_values(rownum))
        wr.writerow(sh.row_values(rownum))
    csvFile.close()

it works but the outputted CSV's have an empty line after each line

"ID","Caption","Sequela type","Visible",""

"infection","Infection","infection","1",""

"acute","Symptomatic infection","acute","1",""

"asymptomatic","Asymptomatic infection","sequela","1",""

"ards_long","Permanent disability due to ARDS","sequela","1",""

"fatalAcute","Fatal cases","sequela","1",""

How can I tell the wr.writerow that it must overwrite the last character?

I think this would eliminate the extra carriage returns.

I tried .strip('\n') but

AttributeError: 'list' object has no attribute 'strip'


Solution

  • You don't need to go back one character. Just use the lineterminator argument for csv writer.

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

    Other thread about this behavior e.g. here.