Asked By – apalopohapa
import csv with open('test.csv', 'w') as outfile: writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) writer.writerow(['hi', 'dude']) writer.writerow(['hi2', 'dude2'])
The above code generates a file,
test.csv, with an extra
\r at each row, like so:
instead of the expected
Why is this happening, or is this actually the desired behavior?
Now we will see solution for issue: CSV in Python adding an extra carriage return, on Windows
with open('output.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) ...
On Windows, always open your files in binary mode (
"wb"), before passing them to
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
\r\n, hence the
\r\r\n observed in the file.
See this previous answer.