You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何避免Python CSV写入时添加末尾换行符?

Avoiding Trailing Newlines in Python CSV Files

I get it—those trailing newlines can be annoying when you split content and end up with an empty string. Let’s break down why this happens and how to fix it.

First, the default csv.writer adds a newline after every row it writes, including the last one. That’s why you’re seeing 'row\nrow2\n' when you read the file. Here are a few practical solutions:

1. Fix it when reading (easiest option!)

Instead of modifying how you write the CSV, adjust your reading code. Python’s splitlines() method is perfect here—it automatically ignores trailing empty strings caused by final newlines:

open('test.csv').read().splitlines()  # Output: ['row', 'row2']

If you prefer using split('\n'), just filter out empty entries:

[row for row in open('test.csv').read().split('\n') if row]

2. Truncate the trailing newline after writing

If you really need the file itself to have no trailing newline, write all your rows first, then trim the last character:

import csv

with open('test.csv', 'w') as f:
    writer = csv.writer(f)
    rows = [['row'], ['row2']]
    writer.writerows(rows)
    
    # Only truncate if we actually wrote rows to avoid errors
    if rows:
        f.seek(f.tell() - 1)  # Move pointer back one byte
        f.truncate()

This works because each writerow adds exactly one newline at the end, so we just remove that last byte.

3. Use a custom CSV writer (more control)

For full control over line endings, you can create a custom writer that skips the newline after the last row:

import csv

class NoTrailingNewlineCSVWriter(csv.writer):
    def writerows(self, rows):
        if not rows:
            return
        
        # Write all rows except the last with normal line endings
        for row in rows[:-1]:
            self.writerow(row)
        
        # Write the last row without the trailing newline
        formatted_last_row = self._format_row(rows[-1])
        # Remove the dialect's line terminator from the end
        self.file.write(formatted_last_row[:-len(self.dialect.lineterminator)])

# Usage
with open('test.csv', 'w') as f:
    writer = NoTrailingNewlineCSVWriter(f)
    writer.writerow(['row'])
    writer.writerow(['row2'])

Personally, I’d go with option 1 unless you have a strict requirement for the file to lack that final newline—it’s the least code and avoids any edge cases with empty files.


Content of the question originates from Stack Exchange, question author: damio

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.15 07:46:11