0
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.

3
  • 1
    take a look at the documentation the only references to newline='' is when opening the file. Commented May 11, 2016 at 14:52
  • so you would want the newline='' in the with open(csvfile,'r', newline='') .. Commented May 11, 2016 at 14:53
  • Thanks! That fixed it. Commented May 11, 2016 at 15:08

2 Answers 2

6

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

See here for examples.

Sign up to request clarification or add additional context in comments.

3 Comments

Firstly thanks for the help. It worked fine. I have one extra question. I essentially have 2 more copies of this that add 2 extra columns excluding this one. When I run the code, they later ones override the previous one. They all create a column in the same place. How do I make one create a column after the other (so they create a column on the next one over)?
@NasifRob what exactly are you trying to do?
You're welcome @NasifRob. Please create a new question for the other problems though, it isn't very easy to help out using the comment section only
1

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])

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.