[英]Writing to a csv file in python
with open("classA.csv" , "a", newline = "") as fp:
a = csv.writer(fp, delimiter = ",")
data = [("{0} has scored: {1} / 10\n ".format(name,score))]
a.writerows(data)
I am trying to create a maths quiz that calculates the final result and then writes this result to an excel file. 我正在尝试创建一个数学测验,以计算最终结果,然后将此结果写入excel文件。 This is my code so far but when I look into excel, I see that the entire statement in data is stretched out across the row and would like this:
到目前为止,这是我的代码,但是当我查看excel时,我发现整个数据语句都在行中延伸,并且需要这样:
| B | o | b | h | a | s | s | c | o | r | e | d | : | 9 | / | 1 | 0
How would I be able to print out like this: 我将如何像这样打印出来:
| Bob has scored: | 9/10 |
Thanks for any help! 谢谢你的帮助!
You need to provide a tuple of columns in the list that you pass to writerows
. 您需要在传递给
writerows
的列表中提供一列元组。
Each element in the tuple will be a column in the resulting file, and all the tuples in the list represent the rows. 元组中的每个元素将是结果文件中的一列,列表中的所有元组都代表行。
For example, if you want to output: 例如,如果要输出:
Bob,2
Joe,3
Bill,5
Then you need to create a list like this: 然后,您需要创建一个像这样的列表:
[('Bob', 2), ('Joe', 3), ('Bill', 5)]
To implement the same in your example, try this version: 要在您的示例中实现相同功能,请尝试以下版本:
col1, col2 = '{} has scored:','{}/10'
with open('classA.csv', 'a') as fp:
writer = csv.writer(fp, delimiter=',')
data = [(col1.format(name), col2.format(score))]
writer.writerows(data)
You also don't need to add the \\n
您也不需要添加
\\n
您的定界符是',',所以您应该尝试: data = [("{0} has scored,{1} / 10\\n ".format(name,score))]
或将定界符设置为':'
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.