Python CSV插入最终换行符-如何避免这种情况? [英] Python CSV insert final newline - how can I avoid it?
问题描述
假设我用两行代码创建了一个csv:
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 import StringIO
import csv
output = StringIO(newline='')
csvfile = csv.writer(output)
csvfile.writerow(['row'])
csvfile.writerow(['row2'])
with open('test.csv', 'w', newline='') as f_output:
f_output.write(output.getvalue().rstrip())
这样做的好处是保留了CSV库的全部功能.不过,我建议您保留尾随换行符.
This has the benefit of preserving the full functionality of the CSV library. I would though recommend you keep the trailing newline.
对于迭代方法:
from io import StringIO
import csv
data = [['row'], ['row2']]
with open('test.csv', 'w', newline='') as f_output:
iter_data = iter(data)
next_row = next(iter_data)
csv_writer = csv.writer(f_output)
for row in iter_data:
csv_writer.writerow(next_row)
next_row = row
# Write the last row to a string to remove trailing newline
last_row = StringIO(newline='')
csv.writer(last_row).writerow(next_row)
f_output.write(last_row.getvalue().rstrip())
这一次将数据写入一行,然后使用StringIO()
方法删除最后一行的换行符,然后处理最后一行.
This writes the data a row at a time and then deals with the last row using the StringIO()
approach to remove the trailing newline.
这篇关于Python CSV插入最终换行符-如何避免这种情况?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!