pythonpython-3.xcsvindex-error

No blank line breaks when writing in a csv file - Python


This is my current code:

import csv


x = 0


with open("new.csv", mode="w") as csv_file:
   fieldnames = ['Question', 'Answer']
   writer = csv.DictWriter(csv_file, fieldnames=fieldnames)
   writer.writeheader()
   while x < 10:
       writer.writerow({"Question": "What's 9+10?", "Answer": "21"})
       x = x + 1

My csv file comes out with the code:

Question,Answer

What's 9+10?,21

What's 9+10?,21

What's 9+10?,21

What's 9+10?,21

What's 9+10?,21

As you can see, there are spaces in between my values.

I want it to look like:

Question,Answer
What's 9+10?,21
What's 9+10?,21
What's 9+10?,21
What's 9+10?,21
What's 9+10?,21

I was expecting this code to write it without the line breaks. This will create issues, for example, if I'm trying to read the code to do the quiz:

score = 0
full = 0
with open("new.csv", mode="r") as csv_file:
    csv_reader = csv.reader(csv_file)
    next(csv_reader)
    for line in csv_reader:
        answer = input(line[0])
        if answer == line[1]:
            print('Correct answer!\n')
            score += 1
            full += 1
        else:
            print('Incorrect, the answer is: ', line[1], '\n')
            full += 1

This in turn will give me the error: IndexError: list index out of range This is because there is a line break, indicating that the index does not exist. I know I can just skip each line break in the for loop, but I would like for the write function to not write a line break. I am going to assume that those spaces are called blank line breaks. If I am wrong, please correct me.


Solution

  • If you check the documentation, you'll see that this problem is described. The standard file I/O wants to add a newline, and the csv module wants to add a newline. You just need to suppress one of them:

    with open("new.csv", "w", newline='') as csv_file: