我写了下面的代码来提取信息。根据文件的第二列对象按字母顺序排列:
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)
每当我试图在命令行上运行此代码时,它会给出错误类型error:“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...
open
内置函数在python 3中得到了newline
关键字,曾经说过,我可以假设您正在使用python 2运行脚本。为了解决您的问题:
python3 myscript.py
。这也许能帮到你。这似乎是一个无效的变量名,您试图做什么。
The error occurs because newline="" is an invalid option for csv.writer(). Changing that should solve the problem. As seen here.
相关问题 更多 >
编程相关推荐