Skip to main content
 首页 » 编程设计

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

2025年05月04日27zhengyun_ustc

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