在 csv 文件中写入时没有空行换行符 - Python

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

提问人:lll 提问时间:11/17/2023 更新时间:11/17/2023 访问量:27

问:

这是我当前的代码:

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

我的 csv 文件带有代码:

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

正如你所看到的,我的价值观之间有空格。

我希望它看起来像:

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

我希望这段代码在没有换行符的情况下编写它。这将产生问题,例如,如果我尝试阅读代码以进行测验:

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

这反过来又会给我一个错误:这是因为有一个换行符,表明索引不存在。我知道我可以跳过for循环中的每个换行符,但我希望write函数不写换行符。我将假设这些空格称为空行符。如果我错了,请纠正我。IndexError: list index out of range

python-3.x csv 索引错误

评论


答:

3赞 Tim Roberts 11/17/2023 #1

如果查看文档,将看到已描述此问题。标准文件 I/O 想要添加换行符,而 csv 模块想要添加换行符。您只需要抑制其中之一:

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