Python 向csv文件添加更多新数据时出现问题

Python 向csv文件添加更多新数据时出现问题,python,python-3.x,csv,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 ro

我写了这个程序,但显然不起作用。我是说代码的最后一部分。程序正在创建文件并向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?)

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

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

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

不幸的是,它仍然没有像以前一样工作:回溯(最近一次调用)文件“/Users/grzegorzspytek/Desktop/python/Sending_automated_mails/nw_csv.py”,第125行,在“Email”:行[“Email”]文件中“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/csv.py”,第155行,在writerow中返回self.writer.writerow(self.\u dict\u to_list(rowdict))文件“/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/tempfile.py”,第481行,在func\u包装器返回func(*args,**kwargs)TypeError:abytes-like对象是必需的,我知道不是'str'。我已经用一个更合适的解决方案更新了我的答案。你试过了吗?我把它放到编译器中,得到了一个要求字符串而不是字节的错误。是的,我试过了。在将模式指定为
w+
后,它工作了。对于二进制模式,默认模式是
w+b
,这就是why
csv.writer
在您的代码中引发异常。我添加了您在上面放弃的行,并将open(“rb”)更改为open(“r+”)。它现在可以工作了。谢谢。
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"]
        })
temp_file = NamedTemporaryFile(mode='w+', delete=False)