Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python3 csv writer failing, exiting on error "TypeError: 'newline' is an invalid keyword argument for this function

Tags:

python-3.x

csv

What I'm trying to do:

I'm trying to change the formatting on a csv file from space delimited to comma delimited.

What I've done:

I can ingest the csv file just fine, and print the output row-by-row to the console. That code looks like this:

with open(txtpath, mode='r', newline='') as f:
    fReader = csv.reader(f)
        for rows in fReader:
            print(rows)

This does exactly what it's supposed to, and spot checking the output confirms that the rows are being read correctly.

The Problem:

According to the official Python3 Documentation on csv.writer, "If csvfile is a file object, it should be opened with newline='' 1." My code looks like this:

with open(csvpath, 'w') as g:
        gWriter = csv.writer(g, newline='')
        gWriter.writerows(rows)

so all together, it looks like this:

with open(txtpath, mode='r', newline='') as f:
    fReader = csv.reader(f)
    for rows in fReader:
        print(rows)
        with open(csvpath, 'w') as g:
            gWriter = csv.writer(g, newline='')
            gWriter.writerows(rows)

However, when I run the code with both Pycharm (Anacondas 3.4 selected as project interpreter) and from the console with python3 mycode.py, both results tell me that newline "is an invalid keyword argument for this function" and references line 42, which is where my writer object is instantiated. I ran it through the debugger and it craps out as soon as I try to create the writer object. If I don't add the newline argument it asks for a dialect specification, so that doesn't work, either.

I'm sure there's something blindingly obvious that I'm missing, but I can't see it.

like image 723
khtad Avatar asked Dec 02 '22 16:12

khtad


1 Answers

To avoid this error , open the file in 'wb' mode instead of 'w' mode. This will eliminate the need for newline. Corrected code is as follows:

with open(csvpath, 'wb') as g:
    gWriter = csv.writer(g)
    gWriter.writerows(rows)
like image 114
Raju Saladi Avatar answered Dec 06 '22 10:12

Raju Saladi