Skip to main content
 首页 » 编程设计

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

2025年04月02日9Renyi-Fan

我有一个名为 studentDetailsCopy 的 CSV 文件,需要在它的末尾添加一行数据,但目前它会将它添加到最后一行的末尾,所以它最终看起来像this: 邮件末尾的a和28是需要在其下方添加的数据(第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) 

请您参考如下方法:

当您使用 open(file,"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)