python - 换行适用于 Windows 但不适用于 Linux

标签 python cross-platform

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

这段代码在 windows 下工作,但在 linux/BSD 下我得到一个错误

异常“未处理的类型错误” 'newline' 是此函数的无效关键字参数

我怎样才能将其重写为跨平台?

最佳答案

听起来您正在使用两个不同版本的 Python,2.x 和 3.x。不幸的是,您必须如何打开 csv 文件取决于所使用的文件——在 Python 3 上,您需要指定 newline='',但在 Python 2 中则不需要,因为它不是有效的关键字参数到 open()

这是我用来打开适用于两个版本的 csv 文件的方法:

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')

关于python - 换行适用于 Windows 但不适用于 Linux,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41913151/

相关文章:

Python 嵌入线程——避免死锁?

python - 如何自己实现tf.argmax?

python - pyGithub最大使用API​​调用率

python : error while saving image from url

Python 多处理 linux windows 区别

bash - 在bash输出中去除字符

python - 使用 setup.py 将数据文件安装到站点包中

c++ - 跨平台浏览器检测

python - 你如何为你的 python 程序制作安装程序?

scala - 设置 scala.js 交叉编译库