Skip to main content
1 of 2
Booboo
  • 3.7k
  • 4
  • 15

I will not repeat what others have so far said.

Open the File Correctly!

@Chris commented that "Nothing about this seems specific to CSV files."

I would go one step further and tell you that the way you are opening files will not always work if its intended use of the file is with the csv module. If you look at the documentation for the csv module, specifically the footnote at the bottom of the page, you will see:

If newline='' is not specified, newlines embedded inside quoted fields will not be interpreted correctly, and on platforms that use \r\n line endings 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.

But this requirement is not specified only in a footnote. If you look at the description for csv.reader on this page you will see:

If csvfile is a file object, it should be opened with newline=''.

And the following example is provided:

import csv
with open('eggs.csv', newline='') as csvfile:
    spamreader = csv.reader(csvfile, delimiter=' ', quotechar='|')
    for row in spamreader:
        print(', '.join(row))

All csv functions that take as an argument an open file should ensure the file is opened specifying newline='' to work correctly for all platforms and CSV contents.

Booboo
  • 3.7k
  • 4
  • 15