在 csv 写入期间返回一个字符
go back one character during csv write
我正在尝试将 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 它必须覆盖最后一个字符?
我认为这会消除额外的回车 returns。
我尝试了 .strip('\n')
但
AttributeError: 'list' object has no attribute 'strip'
如果列表中的字符串需要从中删除 \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
有修改原列表的advantage/disadvantage。您可以在列表 while "\n" in list
.
上致电 remove
你不需要返回一个字符。只需为 csv 编写器使用 lineterminator 参数。
wr = csv.writer(csvFile, lineterminator='\n')
关于此行为的其他话题,例如here.
我正在尝试将 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 它必须覆盖最后一个字符?
我认为这会消除额外的回车 returns。
我尝试了 .strip('\n')
但
AttributeError: 'list' object has no attribute 'strip'
如果列表中的字符串需要从中删除 \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
有修改原列表的advantage/disadvantage。您可以在列表 while "\n" in list
.
remove
你不需要返回一个字符。只需为 csv 编写器使用 lineterminator 参数。
wr = csv.writer(csvFile, lineterminator='\n')
关于此行为的其他话题,例如here.