newline适用于Windows,但不适用于Linux [英] newline works with windows but not linux
问题描述
with open('call.txt', newline='') as inputfile:
phoneNumbers = list(csv.reader(inputfile))
此代码段在Windows下有效,但linux / BSD却报错
this snippet of code works under windows but linux/BSD I get an error
异常未处理的TypeError
换行符是该函数的无效关键字参数
Exception "unhandled TypeError" 'newline' is an invalid keyword argument for this function
如何将其重写为跨平台的?
How can I rewrite this to be cross platform?
推荐答案
听起来您正在使用两个不同版本的Python,即2.x和3.x。不幸的是,打开csv文件的方式因所使用的文件而异-在Python 3上,您需要指定 newline =''
,而在Python 2中则不需要它不是 open()
的有效关键字参数。
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()
.
这是我用来打开在两个版本中均可使用的csv文件的方法:
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')
这篇关于newline适用于Windows,但不适用于Linux的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!