我有一个名为studentDetailsCopy
的CSV文件,需要在其末尾添加一行数据,但此时它会将其添加到最后一行的末尾,因此最终看起来像这样: em>电子邮件末尾的a
和28
是需要在其下方添加的数据(第28行)
这是我的代码:
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)
答案 0 :(得分:1)
当你使用open(文件," a")时,python将始终打开到文件的末尾。由于您的CSV文件没有空的换行符" \ r \ n"在底部,即最后一行是" 26,...",csv writer附加到该行。在此循环中,您应该使用open(文件," a +")读取最后一行,检查它是否为空。如果它不为空,请使用writer.writerow()插入换行符。
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)
答案 1 :(得分:0)
也许可以尝试从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)