Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: 'newline' is an invalid keyword argument for this function [duplicate]

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...
like image 206
user10200421 Avatar asked Aug 14 '18 01:08

user10200421


1 Answers

open built-in function got newline keyword in python 3, once said that, I can 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.
like image 172
slackmart Avatar answered Sep 20 '22 20:09

slackmart