CSV Output File Additional Carriage Return Issue on Windows in Python
When generating CSV files in Python, it's possible to inadvertently add an extra carriage return at the end of each row. This behavior can be observed in the following code:
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'])
Expected Output:
hi,dude hi2,dude2
Actual Output (Windows):
hi,dude\r\r\nhi2,dude2\r\r\n
Causes and Resolution for Python 3:
In Python 3, this issue arises because of the default universal newline translation feature. To resolve it, open the file with newline='' to disable this translation:
with open('output.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) ...
Causes and Resolution for Python 2:
On Windows in Python 2, this issue occurs because CSV is considered a binary format, and rn is the record separator. If the file is opened in text mode, Python replaces the n with rn, resulting in the double carriage return. The solution is to always open files in binary mode:
with open('test.csv', 'wb') as outfile: writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) ...
The above is the detailed content of Why Does My Python CSV Output Have Extra Carriage Returns on Windows?. For more information, please follow other related articles on the PHP Chinese website!