1
with open('call.txt', newline='') as inputfile:
    phoneNumbers = list(csv.reader(inputfile))

this snippet of code works under windows but linux/BSD I get an error

Exception "unhandled TypeError" 'newline' is an invalid keyword argument for this function

How can I rewrite this to be cross platform?

Octo
  • 695
  • 6
  • 20
timypcr
  • 21
  • 3
  • 1
    what versions of python are you using? `newline` arg is only Py3 – AChampion Jan 28 '17 at 18:19
  • Not sure there is a version agnostic way of doing it. Could try the `'U'` mode (assuming universal newline support). This is available in Py2 & 3 but is deprecated and I dislike recommending deprecated options. The other question is why do you need `newlines=''`? – AChampion Jan 28 '17 at 18:27
  • Possible duplicate of [Writing a .CSV file in Python that works for both Python 2.7+ and Python 3.3+ in Windows](http://stackoverflow.com/questions/29840849/writing-a-csv-file-in-python-that-works-for-both-python-2-7-and-python-3-3-in) – cdarke Jan 28 '17 at 18:54

4 Answers4

3

It sounds like you're using two different versions of Python, 2.x and 3.x. Unfortunately how you have to open csv files varies depending on which one is being used—and on Python 3, you need to specify newline='', but not in Python 2 where it's not a valid keyword argument to open().

This is what I use to open csv files that works in both versions:

import sys

def open_csv(filename, mode='r'):
    """ Open a csv file proper way (depends on Python verion). """
    kwargs = (dict(mode=mode+'b') if sys.version_info[0] == 2 else
              dict(mode=mode, newline=''))
    return open(filename, **kwargs)

# sample usage    
csvfile = open_csv('test.csv')
martineau
  • 119,623
  • 25
  • 170
  • 301
  • See http://stackoverflow.com/questions/29840849/writing-a-csv-file-in-python-that-works-for-both-python-2-7-and-python-3-3-in/29841468#29841468 – cdarke Jan 28 '17 at 18:55
  • @cdarke: The logic in your linked answer looks very similar (but is currently hardcoded just for writing files). IMO, while moving the version check out of the function might be more efficient, opening csv files is not something that most programs do often enough to be worth trying to optimize (and creating global variables to hold the results). – martineau Jan 28 '17 at 19:04
2

The issue is not Windows vs. Linux/BSD, it's Python 3 vs Python 2.

The newline argument to open() was added in Python 3 and is not present in Python 2. You should pick one and target a consistent Python version in your script.

Grisha Levit
  • 8,194
  • 2
  • 38
  • 53
0

You probably have an older version of python running on linux.

anserk
  • 1,300
  • 1
  • 9
  • 16
0

thanks everyone was correct. I had two version of python 2 and 3 which the system defaulting to 2. Remove python2 resolved the issue.

timypcr
  • 21
  • 3