Python TypeError: 'newline' is an invalid keyword argument for this function

写一个存为csv文件的代码

 with open(outputFile, 'w', newline='') as csvfile:
     writer = csv.writer(csvfile)
     for item in sortsim:
         writer.writerow([item[0], item[1], item[2]])

出现问题了

Traceback (most recent call last):
  File "/data/ml/shan-als.py", line 54, in 
    with open(outputFile, 'w', newline='') as csvfile:
TypeError: 'newline' is an invalid keyword argument for this function

猜测是版本的原因,加了版本判断。
py2用’wb’,py3可以用newline=’’。

    import sys
    if sys.version >= '3':
        with open(outputFile, 'w', newline='') as csvfile:
            writer = csv.writer(csvfile)
            for item in sortsim:
                writer.writerow([item[0], item[1], item[2]])
    else:
        with open(outputFile, 'wb') as csvfile:
            writer = csv.writer(csvfile)
            for item in sortsim:
                writer.writerow([item[0], item[1], item[2]])

你可能感兴趣的:(DataScience)