What does the `newline=" "` argument do?

Could somebody please explain to me in layman’s terms, what the newline = " " argument does? Documentation is written in a language which only takes me down a rabbit hole of words I don’t understand yet.

4 Likes

Footnotes

[1] (1, 2) If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n linendings on write an extra \r will be added. It should always be safe to specify newline='' , since the csv module does its own (universal) newline handling.

1 Like

That’s the bit which I do not understand. What is meant by “on platforms that use \r\n linendings on write an extra \r will be added.”? Does it mean that the code will accidentally start writing at the beginning of the same line, because of incorrent interpretation? And why do we equate the word “newline” to an empty space as an argument? Am I simply missing some logical connection, or is the answer to that very technical, and I shouldn’t worry about it for now?

2 Likes

Some platforms may insert their own newline escape characters (\n) that conflict with the csv module. It’s sufficient for now to just accept that there is good reason for the recommended implementation and in due course of time you will get more into the technical side of things. I would just pass on this question, for now.

2 Likes

It would appear to overwrite the newline character so there are not two in a row when the module inserts its own. A space (or empty string) are the only substitutions that will not alter the data.

1 Like

I’ve found an interesting explanation in the documentation.

LINK

newline controls how universal newlines mode works (it only applies to text mode). It can be None , '' , '\n' , '\r' , and '\r\n' . It works as follows:

  • When reading input from the stream, if newline is None , universal newlines mode is enabled. Lines in the input can end in '\n' , '\r' , or '\r\n' , and these are translated into '\n' before being returned to the caller. If it is '' , universal newlines mode is enabled, but line endings are returned to the caller untranslated. If it has any of the other legal values, input lines are only terminated by the given string, and the line ending is returned to the caller untranslated.
  • When writing output to the stream, if newline is None , any '\n' characters written are translated to the system default line separator, os.linesep . If newline is '' or '\n' , no translation takes place. If newline is any of the other legal values, any '\n' characters written are translated to the given string.
5 Likes

Could you give an example of an instance where not using newline=’’ would cause an issue?

Not without following up the same information given above, and other SO type questions.