【问题标题】:TypeError: 'newline' is an invalid keyword argument for this function [duplicate]TypeError:“换行符”是此函数的无效关键字参数[重复]
【发布时间】:2019-01-20 18:57:12
【问题描述】:

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

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

【问题讨论】:

标签: python python-3.x


【解决方案1】:

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

【讨论】:

    【解决方案2】:

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

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

    【讨论】:

    • 这本质上是一个仅链接的答案。请总结一下链接的内容。
    • 该链接包含我的问题的解决方案。 Ny 将 'w' 更改为 'wb' 我能够完全摆脱换行符。
    • 一个让提问者满意的答案如何在没有解释的情况下获得否决票?
    • 如果那个问题解决了问题,这个问题应该作为另一个问题的副本关闭,而不是指向另一个问题的答案
    猜你喜欢
    • 1970-01-01
    • 2019-05-17
    • 2012-07-07
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-09-15
    • 1970-01-01
    • 2017-05-04
    相关资源
    最近更新 更多