python-3.x TypeError:尝试open()文件[duplicate]时,“newline”对此函数是无效的关键字参数

wqsoz72f  于 2023-02-26  发布在  Python
关注(0)|答案(2)|浏览(140)
    • 此问题在此处已有答案**:

Writing a .CSV file in Python that works for both Python 2.7+ and Python 3.3+ in Windows(2个答案)
四年前关闭了。
我写了下面的代码,它提取文件的信息,并根据第二列对象按字母顺序排序:

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

9gm1akwq1#

open内置函数在python 3中得到了newline关键字,一旦提到这一点,我可以假设您正在使用python 2运行脚本。
为了解决您的问题:
1.请确保您至少有python v3.2(https://docs.python.org/release/3.2/library/functions.html#open),
1.并使用正确的python版本(例如python3 myscript.py)运行您的程序。

相关问题