问题
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?
回答1:
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')
回答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.
回答3:
You probably have an older version of python running on linux.
回答4:
thanks everyone was correct. I had two version of python 2 and 3 which the system defaulting to 2. Remove python2 resolved the issue.
来源:https://stackoverflow.com/questions/41913151/newline-works-with-windows-but-not-linux