我希望结果的格式为日期,问题,姓名和分数
file = open("results.csv", "a")
file.write('Date, Question, Name, Score\n' + date + ',' question + ',' + name + ',' + score + '\n')
file.close()
当我运行此代码时,我不断收到错误:TypeError:无法转换' int'隐含地反对str
答案 0 :(得分:1)
您必须先将字符串转换为字符串字符串,然后才能将其连接到另一个字符串并写入文件。
str(score) # <-
file.write('Date, Question, Name, Score\n' + date + ',' question + ',' + name + ',' + str(score) + '\n')
或者使用str.format:
with open("results.csv", "a") as f: # with closes your files automatically
f.write('Date, Question, Name, Score\n {}, {}, {}, {}'.format(date, question, name ,score))
您还可以找到csv module有用的
答案 1 :(得分:1)
然后将显式地转换为str:
file.write('Date, Question, Name, Score\n' + str(date) + ',' question + ',' + name + ',' + str(score) + '\n')