Home > Mobile >  What does newline='' mean in the csv library?
What does newline='' mean in the csv library?

Time:12-21

I was reading about CSV library in python, then got stuck in this line: "If csvfile is a file object, it should be opened with newline=''." Could you please explain to me what it means? or give me an example where I can find the exact meaning?

Here, you can find the link to the CSV library with the example: https://docs.python.org/3/library/csv.html#csv-fmt-params

I also highlighted the line in a screenshot but don't know whether you can see it or not.

enter image description here

CodePudding user response:

Python's file objects, by default, use universal newlines when reading files. That means that any of '\n', '\r' and '\r\n' strings are translated into '\n' when you read a file. The csv module doesn't want the file object to do the universal newline translation though, because certain dialects of CSVs allow newline characters to occur within quoted strings.

For example, this could be interpreted as a 3-row CSV, with some kind of a newline in the middle of the string on the second row (which should be preserved in exactly the form it appears in the file, as the newline is part of the data):

1,"foo bar",2
3,"baz
quux",4
5,"spam spam",6

The csv module does its own handling of newlines within Reader objects, so it wants the file object to pass along the newline characters unmodified. That's what newline='' tells the open function you want.

  • Related