python写入csv不换行_Python CSV插入最终换行符-如何避免呢?

当使用Python的csv模块写入CSV文件时,通常会在每一行末尾添加换行符。然而,在某些情况下,可能希望避免这种行为。通过使用StringIO对象并应用rstrip()函数,可以在写入文件之前删除多余的换行符。本文介绍了如何在保持CSV库完整功能的同时,实现这一目标。
摘要由CSDN通过智能技术生成

Let's say I create a csv with two lines:

>>> import csv

>>> csvfile = csv.writer(open('test.csv', 'w'))

>>> csvfile.writerow(['row'])

5

>>> csvfile.writerow(['row2'])

6

When reading it, I get a final new line:

>>> open('test.csv').read()

'row\nrow2\n'

Of course, this can be expected, but in my case I would prefer not to have it since it would be easier to interpret: No need to check for empty lines when doing a split.

>>> open('test.csv').read().split('\n')

['row', 'row2', '']

解决方案

As a workaround you could use a StringIO() object to write to. The output could then have rstrip() applied to it before writing to a file:

from io

  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值