我的代码不是写入csv文件中的新行,而是写在它旁边的同一行

时间:2017-11-28 15:51:22

标签: python csv writer

import csv 
with open ('database1.csv', 'a', newline='') as csvfile:
    linetowrite = username + "," + password + "," + dob + "," +\
                  favartist + "," + favgenre
    csvfile.write(linetowrite)
csvfile.close()

这是我的代码,所有输入都没问题,但似乎有问题,你能帮助我吗?

2 个答案:

答案 0 :(得分:1)

csvfile.write(linetowrite)更改为csvfile.write(linetowrite + "\n")。这会添加一个换行符。

答案 1 :(得分:0)

您正在导入csv模块但从未实际使用过它。为此,您需要创建一个csv.writer,如下所示:

import csv

with open('database1.csv', 'w', newline='') as csvfile:
    csvfilewriter = csv.writer(csvfile)
    csvfilewriter.writerow([username, password, dob, favartist, favgenre])