Nasif Rob
Nasif Rob

Reputation: 37

Invalid Keyword when working with CSV on Python

def c():
    csvfile = 'example.csv'
    with open(csvfile, 'r') as fin, open('new_'+csvfile, 'w') as fout:
        reader = csv.reader(fin, newline='', lineterminator='\n')
        writer = csv.writer(fout, newline='', lineterminator='\n')
        if you_have_headers:
            writer.writerow(next(reader) + [new_heading])
        for row, val in zip(reader, data):
            writer.writerow(row + [data])

Above is some code that I have used to create a column for a CSV file. I keep getting the following error

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

How do I fix this? Thanks in advance.

Upvotes: 0

Views: 9756

Answers (2)

Raju Saladi
Raju Saladi

Reputation: 211

To avoid this error , open the file in 'wb' mode instead of 'w' mode. This will eliminate the need for newline = "", Look below the the corrected code.

csvfile = 'example.csv'
with open(csvfile, 'r') as fin, open('new_'+csvfile, 'wb') as fout:
    reader = csv.reader(fin, newline='', lineterminator='\n')
    writer = csv.writer(fout, lineterminator='\n')
    if you_have_headers:
        writer.writerow(next(reader) + [new_heading])
    for row, val in zip(reader, data):
        writer.writerow(row + [data])

Upvotes: 1

Pep_8_Guardiola
Pep_8_Guardiola

Reputation: 5252

The newline argument should be included within the open function, not the csv reader and writer functions.

See here for examples.

Upvotes: 6

Related Questions