Samuel Lubrano
Samuel Lubrano

Reputation: 47

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: the as and the 28 on the end of the email are the data that needs to be added below it (line 28)

CSV file

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)

Upvotes: 2

Views: 394

Answers (2)

Ross
Ross

Reputation: 1096

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)

Upvotes: 1

RichSmith
RichSmith

Reputation: 940

maybe try removing the brackets from 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)

Upvotes: 0

Related Questions