2016-10-28 109 views
2

我有一個名爲studentDetailsCopy的CSV文件,需要在其末尾添加一行數據,但此刻它將其添加到最後一行的末尾,因此最終看起來像這樣:a s和28在郵件的末尾,需要在其下方添加(第28行)如何使用Python將新數據行添加到CSV文件?

CSV file

這是我的代碼是這樣的數據:

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

當你使用open(文件,「a」)時,python會一直打開到文件末尾。由於CSV文件底部沒有空的換行符「\ r \ n」,即最後一行是「26,...」,因此csv編寫器附加到該行。在這個循環中,你應該使用open(file,「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) 
0

也許嘗試刪除支架s從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) 
+0

恐怕沒有用,我得到了同樣的結果。 –

相關問題