TypeError: 'newline' is an invalid keyword argument for this function, when trying to open() file

Question:

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:

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...
Asked By: user10200421

||

Answers:

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.

Answered By: Tyler_P

open built-in function got the newline keyword in python 3. Given that, I presume you’re running your script using 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.
Answered By: slackmart
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.