向CSV文件中添加更多新数据的问题

时间:2018-10-24 12:46:06

标签: python python-3.x csv

我已经编写了程序,但显然不起作用。我的意思是代码的最后一部分。该程序正在创建文件,并将一些内容添加到csv文件中。代码的最后一部分应该向已经存在的文件中添加更多数据,但是每次我要运行该程序时,都会出现这种错误:

Traceback (most recent call last):
  File "/Users/grzegorzspytek/Desktop/Sending_automated_mails/nw_csv.py", line 121, in <module>
    for row in reader:
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 111, in __next__
    self.fieldnames
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 98, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

之后,我将“打开模式”从“ rb”更改为“ r +”

Traceback (most recent call last):
  File "/Users/grzegorzspytek/Desktop/Sending_automated_mails/nw_csv.py", line 125, in <module>
    "Email": row["Email"]
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py", line 155, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tempfile.py", line 481, in func_wrapper
    return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str' 

似乎我被要求将其改回,但是每次我这样做时,错误都会交替发生。有什么解决办法吗?

这是我程序的代码:

import csv
import shutil
import os
from tempfile import NamedTemporaryFile


def get_len(path):
    with open(path, "r") as csvfile:
        reader = csv.reader(csvfile)
        read_list = list(reader)
    return len(read_list)

#check if this is the file,
def append_data(path, name, email):
    if not os.path.isfile(path):
        with open(path, "w") as csvfile:
            fieldnames = ["ID", "Name", "Email"]
            writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
            writer.writeheader()
            print("Creating file...")

    with open(path, "a") as csvfile:
        fieldnames = ["ID", "Name", "Email"]
        writer = csv.DictWriter(csvfile, fieldnames = fieldnames)
        writer.writerow({
            "ID": get_len(path),
            "Name": name,
            "Email": email
        })
        print("Adding data for " + name)



path = "/Users/grzegorzspytek/Desktop/Sending_automated_mails/data.csv"
append_data(path, "grzesiek", "grz.spy")

filename = "data.csv"
temp_file = NamedTemporaryFile(delete=False)





with open("data.csv", "rb") as csvfile, temp_file:
    reader = csv.DictReader(csvfile)
    fieldnames = ["ID", "Name", "Email"]
    writer = csv.DictWriter(temp_file, fieldnames = fieldnames)
    for row in reader:
        writer.writerow({
            "ID": row["ID"],
            "Name": row["Name"],
            "Email": row["Email"]
        })

1 个答案:

答案 0 :(得分:1)

您应该改为以文本模式打开临时文件:

temp_file = NamedTemporaryFile(mode='w+', delete=False)

否则,默认情况下以二进制文件documented的形式打开临时文件。