【问题标题】:How do I add a new row of data to a CSV file with Python?如何使用 Python 将新数据行添加到 CSV 文件?
【发布时间】:2017-03-11 07:29:38
【问题描述】:

我有一个名为 studentDetailsCopy 的 CSV 文件,需要在其末尾添加一行数据,但目前它会将其添加到最后一行的末尾,因此最终看起来像这样:电子邮件末尾的as 和28 是需要在其下方添加的数据(第28 行)

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)

【问题讨论】:

    标签: python csv


    【解决方案1】:

    当您使用 open(file,"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)
    

    【讨论】:

      【解决方案2】:

      也许尝试从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)
      

      【讨论】:

      • 恐怕这不起作用,我得到了相同的结果。
      猜你喜欢
      • 1970-01-01
      • 2022-01-07
      • 1970-01-01
      • 2011-04-28
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多