如何避免Python CSV写入时添加末尾换行符?
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

