3

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)

2 Answers 2

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.

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)
Sign up to request clarification or add additional context in comments.

Comments

0

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)

1 Comment

I'm afraid that that didn't work, I'm getting the same result.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.