[Tutor] Terminating "\M" characters with regard to csv.DictWriter
Alex Kleider
alexkleider at gmail.com
Tue Aug 10 00:03:53 EDT 2021
On Mon, Aug 9, 2021 at 1:14 AM Peter Otten <__peter__ at web.de> wrote:
> As explained by others the ^M or chr(13) or "\r" is part of a windows
> line ending "\r\n".
> I'd like to clarify that it is *not* inserted by the file object but by
> the csv.writer(). Its default dialect is "excel" which writes "\r\n" as
> the line separator regardless of the operating system's line terminator
> (os.linesep). To avoid it you can either override the line terminator with
>
> # excel dialect, but with newlines only
> writer = csv.writer(outstream, lineterminator="\n")
>
This solved my problem; Thank you very much for the suggestion.
>
> or pick a different dialect
>
> writer = csv.writer(outstream, dialect="unix")
>
>
> This got rid of the '\M' at the end of each line but created a new problem
in that each field was in quotes!!
Thanks again for taking the trouble of helping.
Cheers,
Alex
PS I need to ponder the following a bit more:-)
>>> f = open("tmp.csv", "w", newline="")
> >>> csv.writer(f).dialect.lineterminator
> '\r\n'
> >>> csv.writer(f, lineterminator="\n").dialect.lineterminator
> '\n'
> >>> csv.writer(f, dialect="unix").dialect.lineterminator
> '\n'
>
More information about the Tutor
mailing list