Python TypeError: 'newline' 是此函数的无效关键字参数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51832593/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-19 19:56:21  来源:igfitidea点击:

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

pythonpython-3.x

提问by user10200421

I wrote the following code which extracts the info. of a file and orders it alphabetically based on its second column objects:

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

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)

Whenever I try to run this code on the command line, it gives me the error TypeError: 'newline' is an invalid keyword argument for this function. Do you guys see reasons why this may be happening. The following if a structured version of the contents in the file:

每当我尝试在命令行上运行此代码时,它都会给我错误 TypeError: 'newline' is an invalid keyword argument for this function。你们知道这可能发生的原因吗?以下是文件内容的结构化版本:

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...

采纳答案by Tyler_P

This may be able to help you out. It seems like that is an invalid variable name for what you are trying to do.

这或许能帮到你。对于您要执行的操作,这似乎是一个无效的变量名称。

The error occurs because newline="" is an invalid option for csv.writer(). Changing that should solve the problem. As seen here.

发生错误是因为 newline="" 是 csv.writer() 的无效选项。改变它应该可以解决问题。如这里所见。

回答by slackmart

openbuilt-in function got newlinekeyword in python 3, once said that, I can presume you're running your script using python 2.

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

In order to solve your issue:

为了解决您的问题:

  1. make sure you have at least python v3.2 (https://docs.python.org/release/3.2/library/functions.html#open),
  2. and run your program using the right python version, e.g. python3 myscript.py.
  1. 确保你至少有 python v3.2 ( https://docs.python.org/release/3.2/library/functions.html#open),
  2. 并使用正确的 python 版本运行你的程序,例如python3 myscript.py.