Csv file written with Python has blank lines between each row
To eliminate blank lines in a CSV file when using Python on Windows, set the newline
parameter to an empty string ''
when opening the file. This stops the CSV module from adding extra newline characters:
Always use open
with newline=''
to prevent sneakily snuck-in line breaks in your CSV output.
Addressing version-specific CSV writing quirks
Let's dive deeper and tackle some CSV writing gotchas specific to different Python versions and use-cases.
Python 2: Beware of unexpected blank lines
If you're coding in Python 2, remember to open your files in binary mode using wb
instead of w
. This ward-off unnecessary newline translation causing those annoying blank lines.
Unicode handling in Python 2
Is your CSV data rich in Unicode strings? Fear not my friend, unicodecsv
module comes to your rescue when you're using Python 2.
Custom line terminator control
Default settings are comfortable, but sometimes you may want to take control of the line terminator. Go ahead, be the boss of your line endings!
StringIO - The in-memory CSV lifesaver
Building up a CSV in memory before hitting the disk? StringIO
is your new best friend:
Python 3.10+: The Path
to easy file writing
If you're on Python 3.10 or newer, enjoy easy and succinct file handling with the Path
object from pathlib
:
Catering to various use cases
Now let's add more tools to your CSV-writing toolkit for a range of scenarios:
For Excel files, just switch the newline
When your CSV files are going to be read by Excel, stick to the newline=''
rule because Excel likes newlines with \r\n
.
Quoted Fields and CSV
We've all seen CSV fields perfectly encapsulating line breaks within quotes. To parse these correctly, it's vital to specify newline=''
.
Large data and memory efficiency
When crunching large data sets, it's more memory-efficient to write results incrementally rather than building up the entire result in memory:
Use pathlib.Path for modern file handling
With the modern Path
module, handling file operations becomes a breeze, due to its precise and readable syntax:
Was this article helpful?