In Python 2: Open the file in binary mode, always;
with open(filename, 'ab') as outputfile: writer = csv.DictWriter(outputfile, fieldnames)
If csvfile is a file object, it must be opened with the ‘b’ flag on platforms where that makes a difference.
In Python 3: Open the file with
csv.DictWriter()can control the newlines written without translation:
with open(filename, 'a', newline="") as outputfile: writer = csv.DictWriter(outputfile, fieldnames)
Again, quoting the relevant
If csvfile is a file object, it should be opened with
[ … ]
newline=""is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use
\r\nlinendings on write an extra
\rwill be added. It should always be safe to specify
newline="", since the csv module does its own (universal) newline handling.