本文介绍了如何使用Python将新的数据行添加到CSV文件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have a CSV file called studentDetailsCopy and need to add a row of data to the end of it but at the moment it adds it to the end of the last row so it ends up looking like this: the as and the 28 on the end of the email are the data that needs to be added below it (line 28)

CSV文件

这是我执行此操作的代码:

This is my code that is doing this:

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 writer会追加到该行.在此循环中,您应该使用open(file,"a +")阅读最后一行,并检查其是否为空.如果不为空,请执行writer.writerow()插入换行符.

When you use open(file,"a") python will always open to the end of the file. Since your CSV file does not have an empty newline "\r\n" at the bottom, i.e the last line is "26,...", csv writer appends to that line. In this loop you should read the last line using open(file,"a+"), check to see that it is empty. If it is not empty do writer.writerow() to insert a newline.

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)

这篇关于如何使用Python将新的数据行添加到CSV文件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 09:58
查看更多