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

kjthegm6  于 2023-11-20  发布在  Python
关注(0)|答案(1)|浏览(121)

这是我现在的代码:

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


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

dxpyg8gm

dxpyg8gm1#

如果你查看文档,你会看到这个问题是描述的,标准文件I/O想要添加一个换行符,而csv模块想要添加一个换行符,你只需要抑制其中一个:

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

字符串

相关问题