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

时间:2016-10-28 11:52:47

标签: python csv

我有一个名为studentDetailsCopy的CSV文件,需要在其末尾添加一行数据,但此时它会将其添加到最后一行的末尾,因此最终看起来像这样: em>电子邮件末尾的a28是需要在其下方添加的数据(第28行)

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)

2 个答案:

答案 0 :(得分:1)

当你使用open(文件," a")时,python将始终打开到文件的末尾。由于您的CSV文件没有空的换行符" \ r \ n"在底部,即最后一行是" 26,...",csv writer附加到该行。在此循环中,您应该使用open(文件," 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)

答案 1 :(得分:0)

也许可以尝试从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)