Python 3:

The official csv documentation recommends opening the file with newline='' on all platforms to disable universal newlines translation:

with open('output.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    ...

The CSV writer terminates each line with the lineterminator of the dialect, which is '\r\n' for the default excel dialect on all platforms because that's what RFC 4180 recommends.


Python 2:

On Windows, always open your files in binary mode ("rb" or "wb"), before passing them to csv.reader or csv.writer.

Although the file is a text file, CSV is regarded a binary format by the libraries involved, with \r\n separating records. If that separator is written in text mode, the Python runtime replaces the \n with \r\n, hence the \r\r\n observed in the file.

See this previous answer.

Answer from John Machin on Stack Overflow
Top answer
1 of 6
540

Python 3:

The official csv documentation recommends opening the file with newline='' on all platforms to disable universal newlines translation:

with open('output.csv', 'w', newline='', encoding='utf-8') as f:
    writer = csv.writer(f)
    ...

The CSV writer terminates each line with the lineterminator of the dialect, which is '\r\n' for the default excel dialect on all platforms because that's what RFC 4180 recommends.


Python 2:

On Windows, always open your files in binary mode ("rb" or "wb"), before passing them to csv.reader or csv.writer.

Although the file is a text file, CSV is regarded a binary format by the libraries involved, with \r\n separating records. If that separator is written in text mode, the Python runtime replaces the \n with \r\n, hence the \r\r\n observed in the file.

See this previous answer.

2 of 6
291

While @john-machin gives a good answer, it's not always the best approach. For example, it doesn't work on Python 3 unless you encode all of your inputs to the CSV writer. Also, it doesn't address the issue if the script wants to use sys.stdout as the stream.

I suggest instead setting the 'lineterminator' attribute when creating the writer:

import csv
import sys

doc = csv.writer(sys.stdout, lineterminator='\n')
doc.writerow('abc')
doc.writerow(range(3))

That example will work on Python 2 and Python 3 and won't produce the unwanted newline characters. Note, however, that it may produce undesirable newlines (omitting the LF character on Unix operating systems).

In most cases, however, I believe that behavior is preferable and more natural than treating all CSV as a binary format. I provide this answer as an alternative for your consideration.

🌐
Reddit
reddit.com › r/learnpython › how to remove '\r\n' from the csv records being written?
r/learnpython on Reddit: How to remove '\r\n' from the csv records being written?
July 30, 2015 -

I am running the script on a Windows 7 machine using Python 3.4.1. The script runs correctly and produces a csv file, the only problem is at the end of each line is a '\r\n' which causes an extra blank line to appear when displayed in Excel. How do get remove the extra blank line?

import pyodbc
import csv

connect = pyodbc.connect('driver={SQL Server Native       Client 10.0};SERVER=xxxxx-7-   VM;DATABASE=DEMO_xxxx_TEST;UID=DEMO_xxxx_TEST;PWD=password')

cursor = connect.cursor()

cursor.execute('''select Report_name
                    ,UserID
                    ,FieldName
                    ,XPos
                    ,YPos
                    ,Hidden
                    ,Picture
              from  Rpt_Nudge_2
              where Report_Name = 'UB04' and UserID = 'myid' and YPos > 8886 and YPos < 9888
              order by YPos, XPos''')

col_names = [i[0] for i in cursor.description]
print(col_names)

nudge = cursor.fetchall()

with open('UB04_nudge.csv', 'w') as csvfile:
    fileout = csv.writer(csvfile)
    row = fileout.writerow(col_names)
    for line in nudge:
        fileout.writerow(line)

connect.close()
🌐
Reddit
reddit.com › r/learnpython › csv writer: append doesn't go to new line
r/learnpython on Reddit: csv writer: append doesn't go to new line
January 26, 2021 -

So, basically, I've got this code:

new_list_csv = []

def add_it():
    #gets the values from Entry
    #three different tk Entrys generate three different values
    name= self.e.get()
    ex= self.e_x.get()
    ey= self.e_y.get()
    #adds them to the new list
    new_list_csv.append(name)
    new_list_csv.append(ex)
    new_list_csv.append(ey)
    #appends new characters to csv file
    with open ('chr_list_copy.txt', 'a', newline='') as write_obj:   
        csv_writer = csv.writer(write_obj)
        csv_writer.writerow(new_list_csv)

and the csv file looks like this:

name,x,y
Ergo,1,1
Sum,5,5
Name12,1,2
Name34,3,4
Name56,5,6
Name78,7,8
Name910,9,10
Name1112,11,12
Name1314,13,14

if I try and add [Otto,6,9], I get:

name,x,y
[...]
Name1314,13,14Otto,6,9

instead of:

name,x,y
[...]
Name1314,13,14
Otto,6,9

I've used this very same structure for the rest of my code, but in this specific instance, it doesn't work.

🌐
w3resource
w3resource.com › python-exercises › modules › python-module-csv-exercise-6.php
Python: Write (without writing separate lines between rows) and read a CSV file with specified delimiter - w3resource
August 11, 2025 - Use csv.reader ... import csv fw = open("test.csv", "w", newline='') writer = csv.writer(fw, delimiter = ",") writer.writerow(["a","b","c"]) writer.writerow(["d","e","f"]) writer.writerow(["g","h","i"]) fw.close() fr = open("test.csv", "r") ...
🌐
Sopython
sopython.com › canon › 97 › writing-csv-adds-blank-lines-between-rows
Writing CSV adds blank lines between rows - sopython
In Python 3, leave the file in text mode, since you’re writing text, but disable universal newlines. with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile: writer = csv.writer(outfile)
🌐
Python
bugs.python.org › issue7198
Issue 7198: Extraneous newlines with csv.writer on Windows - Python tracker
This issue tracker has been migrated to GitHub, and is currently read-only. For more information, see the GitHub FAQs in the Python's Developer Guide · This issue has been migrated to GitHub: https://github.com/python/cpython/issues/51447
Find elsewhere
🌐
KnowledgeHut
knowledgehut.com › https://www.knowledgehut.com › tutorials › programming tutorials
Python CSV Tutorial: Read, Write & Manipulate CSV Files in Python
Instead of iterating over the list we could also have used writerows() method. >>> csvfile=open(marks.csv','w', newline='') >>> obj=csv.writer(csvfile) >>> obj.writerows(marks) >>> obj.close()
Top answer
1 of 11
1443

The csv.writer module directly controls line endings and writes \r\n into the file directly. In Python 3 the file must be opened in untranslated text mode with the parameters 'w', newline='' (empty string) or it will write \r\r\n on Windows, where the default text mode will translate each \n into \r\n.

#!python3
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
    writer = csv.writer(outfile)

If using the Path module:

from pathlib import Path
import csv

with Path('/pythonwork/thefile_subset11.csv').open('w', newline='') as outfile:
    writer = csv.writer(outfile)

If using the StringIO module to build an in-memory result, the result string will contain the translated line terminator:

from io import StringIO
import csv

s = StringIO()
writer = csv.writer(s)
writer.writerow([1,2,3])
print(repr(s.getvalue()))  # '1,2,3\r\n'   (Windows result)

If writing that string to a file later, remember to use newline='':

# built-in open()
with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as f:
    f.write(s.getvalue())

# Path's open()
with Path('/pythonwork/thefile_subset11.csv').open('w', newline='') as f:
    f.write(s.getvalue())

# Path's write_text() added the newline parameter to Python 3.10.
Path('/pythonwork/thefile_subset11.csv').write_text(s.getvalue(), newline='')

In Python 2, use binary mode to open outfile with mode 'wb' instead of 'w' to prevent Windows newline translation. Python 2 also has problems with Unicode and requires other workarounds to write non-ASCII text. See the Python 2 link below and the UnicodeReader and UnicodeWriter examples at the end of the page if you have to deal with writing Unicode strings to CSVs on Python 2, or look into the 3rd party unicodecsv module:

#!python2
with open('/pythonwork/thefile_subset11.csv', 'wb') as outfile:
    writer = csv.writer(outfile)

Documentation Links

  • https://docs.python.org/3/library/csv.html#csv.writer
  • https://docs.python.org/2/library/csv.html#csv.writer
2 of 11
93

Opening the file in binary mode "wb" will not work in Python 3+. Or rather, you'd have to convert your data to binary before writing it. That's just a hassle.

Instead, you should keep it in text mode, but override the newline as empty. Like so:

with open('/pythonwork/thefile_subset11.csv', 'w', newline='') as outfile:
🌐
Python
docs.python.org › 3.4 › library › csv.html
14.1. csv — CSV File Reading and Writing — Python 3.4.10 documentation
July 16, 2019 - While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written. ... import csv with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam'])
🌐
Python Morsels
pythonmorsels.com › csv-writing
Writing a CSV file - Python Morsels
February 14, 2023 - You could use a for loop along with the writerow method: >>> import csv >>> with open("cities.csv", mode="wt", newline="") as csv_file: ... writer = csv.writer(csv_file) ... for row in cities: ... writer.writerow(row) ...
🌐
Python
docs.python.org › 3 › library › csv.html
csv — CSV File Reading and Writing
While this isn’t a reversible transformation, it makes it easier to dump SQL NULL data values to CSV files without preprocessing the data returned from a cursor.fetch* call. All other non-string data are stringified with str() before being written. A short usage example: import csv with open('eggs.csv', 'w', newline='') as csvfile: spamwriter = csv.writer(csvfile, delimiter=' ', quotechar='|', quoting=csv.QUOTE_MINIMAL) spamwriter.writerow(['Spam'] * 5 + ['Baked Beans']) spamwriter.writerow(['Spam', 'Lovely Spam', 'Wonderful Spam']) which writes eggs.csv containing: Spam Spam Spam Spam Spam |Baked Beans| Spam |Lovely Spam| |Wonderful Spam| csv.register_dialect(name, /, dialect='excel', **fmtparams)¶ ·
🌐
Python Forum
python-forum.io › thread-11752.html
python export to csv writes extra line between rows
July 24, 2018 - I am having issues with the following export from sql table to csv. the output file is creating a extra line between each row, i need to resolve this. to include the headers and rows without extra line import pyodbc import csv conn = pyodbc. connect...
🌐
Stack Overflow
stackoverflow.com › questions › 68371640
Python Module CSV adds a blank line between writen lines in a CSV file - Stack Overflow
July 14, 2021 - Copyfrom csv import writer with open('movies.csv', 'w') as file: writer_csv = writer(file) movie = None writer_csv.writerow(['Title', 'Genre', 'Lenght']) while movie != 'finish': movie = input('Movie name: ') if movie != 'finish': genre = input('Genre: ') lenght = input('Lenght: ') writer_csv.writerow([movie, genre, lenght]) Everything works fine, but the extra blank line. The result is... CopyTitle,Genre,Lenght Bourne Identity,Action,120 Bourne Supremacy,Action,125 Ultimatum Bourne,Action,128 · And the desired result is... CopyTitle,Genre,Lenght Bourne Identity,Action,120 Bourne Supremacy,Action,125 Ultimatum Bourne,Action,128 · Thank's for any help! ... This solved the undesired line break: with open('movies.csv', 'w', newline='') as file: (found here)
🌐
Frankcorso
frankcorso.me › frank corso › reading from writing to csv files python
Reading From and Writing to CSV Files in Python - Frank Corso
May 12, 2025 - with open('somefile.csv', newline='', encoding='utf-8') as fh: # Do stuff · To get started, let's do a simple exercise of writing a row to a new file and then reading that row. To work with CSV files, we first need to import the csv module. ... Then, we will use its writer() method to create a writer object that will perform the writing for us. We will then use its writerow() method to write a row in our CSV.
🌐
Reddit
reddit.com › r/learnpython › why csv.writer leaves empty space in between rows, like i mentioned below? and how can i prevent this?
r/learnpython on Reddit: Why csv.writer leaves empty space in between rows, like I mentioned below? and how can I prevent this?
July 19, 2024 -
import csv

name=input("What's its name? ")
type=input("What's its type? ")
with open("fruits2.csv","a") as file:
    writer=csv.writer(file,delimiter="-") 
    writer.writerow([name, type]) 


apple-fruit

pear-fruit

pizza-food