Skip to content Skip to sidebar Skip to footer

How Do I Add A New Row Of Data To A Csv File With Python?

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:

Solution 1:

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.

withopen('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)

Solution 2:

maybe try removing the brackets from newStudentAttributes?

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

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

Post a Comment for "How Do I Add A New Row Of Data To A Csv File With Python?"