1

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'

stallingOne
  • 3,633
  • 3
  • 41
  • 63
  • Try `[s for s in mystrings if s != '\n']` or if you want to eliminate all strings containing newlines, `[s for s in mystrings if '\n' not in s]` – machine yearning May 25 '16 at 12:31

2 Answers2

3

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.

Daniel
  • 897
  • 6
  • 11
  • Awesome, always let the library do the string processing for you unless you have a good reason not to! I knew there was a good answer to this question. – machine yearning May 25 '16 at 13:58
0

If the strings in the list need to have \n removed from them, use strip:

>> a = ["\nfrog", "\ncow", "\nsnake"]
>> print map(str.strip, a)
['frog', 'cow', 'snake']

If the list needs to have \n removed from it, try remove for a single item or a list comprehension like this for all of them:

b = [x for x in a if not x == "\n"]

remove has the advantage/disadvantage of modifying the original list. You could call remove on the list while "\n" in list.

Jeremy Weirich
  • 387
  • 5
  • 20
  • 1
    I love `map` the functional paradigm but it's more idiomatic and considered more readable in python to use comprehensions, i.e. `[x.strip() for x in a]` – machine yearning May 25 '16 at 12:29
  • it's the list that has a `\n` too much, not each element of the list. (because here a list is a CSV line and an element of the list is 1 value) I tried `wr.writerow(map(str.strip, sh.row_values(rownum)))` but it doesn't work, same error – stallingOne May 25 '16 at 12:30