TypeError:“ newline”是此函数的无效关键字参数

时间:2018-08-14 01:36:51

标签: python python-3.x

我编写了以下代码来提取信息。文件并根据其第二列对象按字母顺序排序:

import csv
import operator
import sys

def re_sort(in_file='books.csv', out_file='books_sort.csv'):
    data = csv.reader(open('books.csv', newline=''), delimiter=',')
    header = next(data)
    sortedlist = sorted(data, key=operator.itemgetter(1))
    with open("books_sorted.csv", "w", newline='') as csvfile:
        cvsWriter = csv.writer(csvfile, delimiter=',')
        cvsWriter.writerow(header)
        cvsWriter.writerows(sortedlist)

每当我尝试在命令行上运行此代码时,都会出现错误TypeError:'newline'是此函数的无效关键字参数。你们看到发生这种情况的原因了吗?以下是文件内容的结构化版本:

Title,            Author,        Publisher,  Year,  ISBN-10,   ISBN-13
Automate the...,  Al Sweigart,   No Sta...,  2015,  15932...,  978-15932...
Dive into Py...,  Mark Pilgr..., Apress,     2009,  14302...,  978-14302...
"Python Cook...,  "David Bea..., O'Reil...,  2013,  14493...,  978-14493...
Think Python...,  Allen B. D..., O'Reil...,  2015,  14919...,  978-14919...
"Fluent Pyth...,  Luciano Ra..., O'Reil...,  2015,  14919...,  978-14919...

2 个答案:

答案 0 :(得分:4)

open内置函数在python 3中获得了newline关键字,有人说过,我可以假设您正在使用python 2运行脚本。

为了解决您的问题:

  1. 确保您至少具有python v3.2(https://docs.python.org/release/3.2/library/functions.html#open),
  2. 并使用正确的python版本运行程序,例如python3 myscript.py

答案 1 :(得分:-2)