In Python code that writes CSV files, you may encounter an issue where each row is appended with an extra carriage return ("r") on Windows systems. This unexpected behavior can make the generated CSV file incompatible with some applications or systems.
To understand why this happens, let's analyze the provided code snippet:
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'])
In Python 3, the default behavior for CSV writing is to use universal newlines translation. This means that on Windows, the "rn" line terminator is automatically converted to a single "n". However, when opening the file with "w" mode, this translation is disabled. As a result, the writer appends "rn" after each row.
To disable universal newline translation, use the newline='' parameter when opening the file:
with open('output.csv', 'w', newline='', encoding='utf-8') as f: writer = csv.writer(f) ...
In Python 2, binary mode ("rb" or "wb") must be used when opening files for CSV reading or writing on Windows:
with open('test.csv', 'wb') as outfile: writer = csv.writer(outfile, delimiter=',', quoting=csv.QUOTE_MINIMAL) ...
By opening the file in binary mode, newline conversion is avoided, ensuring that "rn" is written to the file as intended.
The above is the detailed content of Why Are Extra Carriage Returns Added to My CSV Files on Windows?. For more information, please follow other related articles on the PHP Chinese website!