如何使用Python将新数据行添加到CSV文件?

问题描述:

我有一个名为studentDetailsCopy的CSV文件,需要在其末尾添加一行数据,但此刻它将其添加到最后一行的末尾,因此最终看起来像这样:a s和28在邮件的末尾,需要在其下方添加(第28行)如何使用Python将新数据行添加到CSV文件?

CSV file

这是我的代码是这样的数据:

newStudentAttributes = ([str(lastRowInt), newSurname, newForename, newDoB, newAddress, newHomePhoneNumber, newGender, newTutorGroup, newSchoolEmail]) 

with open('studentDetailsCopy.csv', 'a') as studentDetailsCSV: 
    writer = csv.writer(studentDetailsCSV, dialect='excel') 
    writer.writerow(newStudentAttributes) 

当你使用open(文件,“a”)时,python会一直打开到文件末尾。由于CSV文件底部没有空的换行符“\ r \ n”,即最后一行是“26,...”,因此csv编写器附加到该行。在这个循环中,你应该使用open(file,“a +”)读取最后一行,检查它是否为空。如果它不为空,则使用writer.writerow()插入一个换行符。

with open('studentDetailsCopy.csv', 'a+') as studentDetailsCSV: 
    # Go to the last row, jump before the EOF terminator 
    studentDetailsCSV.seek(-2,2) 
    line = studentDetailsCSV.readline() 
    writer = csv.writer(studentDetailsCSV, dialect='excel') 
    #If the line is more than just a terminator, insert a newline. 
    if line != "\r\n": 
     writer.writerow("") 
    writer.writerow(newStudentAttributes) 

也许尝试删除支架s从newStudentAttributes

newStudentAttributes = [ 
    str(lastRowInt), 
    newSurname, 
    newForename, 
    newDoB, 
    newAddress, 
    newHomePhoneNumber, 
    newGender, 
    newTutorGroup, 
    newSchoolEmail 
] 

with open('studentDetailsCopy.csv', 'a') as studentDetailsCSV: 
    writer = csv.writer(studentDetailsCSV, dialect='excel') 
    writer.writerow(newStudentAttributes) 
+0

恐怕没有用,我得到了同样的结果。 –