如何使用Python向CSV文件添加新的数据行?

2024-09-30 08:15:24 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个名为studentDetailsCopy的CSV文件,需要在它的末尾添加一行数据,但此时它将它添加到最后一行的末尾,所以结果如下:电子邮件末尾的a和{}是需要添加到它下面的数据(第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)

Tags: 文件csv数据代码电子邮件filewriter末尾
2条回答

当您使用open(file,“a”)时,python将始终打开到文件的末尾。由于您的CSV文件底部没有空换行“\r\n”,即最后一行是“26,…”,CSV writer会附加到该行。在这个循环中,您应该使用open(file,“a+”)读取最后一行,检查它是否为空。如果不是空的话就做作家.作家()插入新行。在

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)

也许试着把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)

相关问题 更多 >

    热门问题