python向csv添加行_如何使用Python将新的数据行添加到CSV文件?

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)

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)

解决方案

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)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值