向 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"]
})

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

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

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

最新更新