在csv写

时间:2016-05-25 12:16:40

标签: python csv xlrd

我正在尝试将xls表格转换为CSV文件。

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

它可以工作,但输出的CSV在每行之后都有一个空行

"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",""

我如何告诉wr.writerow它必须覆盖最后一个字符?

我认为这会消除额外的回车。

我尝试了.strip('\n')但是

  

AttributeError:'list'对象没有属性'strip'

2 个答案:

答案 0 :(得分:3)

你不需要回到一个角色。只需使用csv writer的lineterminator参数。

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

有关此行为的其他帖子,例如here

答案 1 :(得分:0)

如果列表中的字符串需要从中删除\n,请使用strip

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

如果列表需要从中删除\n,请尝试remove获取单个项目,或者对所有这些项目执行类似的列表理解:

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

remove具有修改原始列表的优点/缺点。您可以在列表remove上致电while "\n" in list