Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

What does newline='' mean in the csv library?

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

enter image description here

Bests

>Solution :

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.

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading