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
TypeError: 'newline' is an invalid keyword argument for this function
提问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.
这或许能帮到你。对于您要执行的操作,这似乎是一个无效的变量名称。
回答by slackmart
open
built-in function got newline
keyword 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:
为了解决您的问题:
- make sure you have at least python v3.2 (https://docs.python.org/release/3.2/library/functions.html#open),
- and run your program using the right python version, e.g.
python3 myscript.py
.
- 确保你至少有 python v3.2 ( https://docs.python.org/release/3.2/library/functions.html#open),
- 并使用正确的 python 版本运行你的程序,例如
python3 myscript.py
.