有人可以告诉我为什么我在python 3上收到以下错误。以下是追溯:
TypeError
Traceback (most recent call last) <ipython-input-24-a81d4875414b> in <module>()
7 filename = [("id"), ("name"), ("email"), ("amount"),("sent")]
8 writer= csv.DictWriter(temp_file, fieldnames = fieldnames)
----> 9 writer.writeheader()
10
11 for row in reader:
C:\Users\johsc_001\AppData\Local\conda\conda\envs\ipykernel_py3\lib\csv.py in writeheader(self)
142 def writeheader(self):
143 header = dict(zip(self.fieldnames, self.fieldnames))
--> 144 self.writerow(header)
145
146 def _dict_to_list(self, rowdict):
C:\Users\johsc_001\AppData\Local\conda\conda\envs\ipykernel_py3\lib\csv.py in writerow(self, rowdict)
153
154 def writerow(self, rowdict):
--> 155 return self.writer.writerow(self._dict_to_list(rowdict))
156
157 def writerows(self, rowdicts):
C:\Users\johsc_001\AppData\Local\conda\conda\envs\ipykernel_py3\lib\tempfile.py in func_wrapper(*args, **kwargs)
481 @_functools.wraps(func)
482 def func_wrapper(*args, **kwargs):
--> 483 return func(*args, **kwargs)
484 # Avoid closing the file as long as the wrapper is alive,
485 # see issue #18879.
TypeError: a bytes-like object is required, not 'str'
这是源代码:
import csv
import shutil
from tempfile import NamedTemporaryFile
filename = 'appendpyt2.csv'
temp_file = NamedTemporaryFile(delete= False)
with open(filename, 'rb')as csvfile, temp_file:
reader =csv.DictReader(csvfile)
filename = ["id", "name", "email", "amount", "sent"]
writer= csv.DictWriter(temp_file, fieldnames = ["id", "name", "email","amout", "sent"])
writer.writeheader()
for row in reader:
print(row)
writer.writerow({
"id": row["id"],
"name": row["name"],
"email":row["email"],
"amout":"1234.56",
"sent": ""
})
答案 0 :(得分:0)
错误似乎来自使用Python 3,但使用Python 2要求打开csv
文件。如果使用Python 3,则不应以二进制模式打开CSV文件,并且newline参数应为空字符串。临时文件也默认为二进制模式,所以我重写了它。我还使用以下作为输入文件,从代码推导出来,因为没有提供样本输入。
<强> appendpyt2.csv:
id,name,email
id1,name1,email1
id2,name2,email2
Python 3代码:
import csv
import shutil
from tempfile import NamedTemporaryFile
filename = 'appendpyt2.csv'
temp_file = NamedTemporaryFile(mode='w+',newline='',delete= False)
with open(filename,newline='') as csvfile, temp_file:
reader =csv.DictReader(csvfile)
filename = ["id", "name", "email", "amount", "sent"]
writer= csv.DictWriter(temp_file, fieldnames = ["id", "name", "email","amount", "sent"])
writer.writeheader()
for row in reader:
print(row)
writer.writerow({
"id": row["id"],
"name": row["name"],
"email":row["email"],
"amount":"1234.56",
"sent": ""
})
临时文件输出:
id,name,email,amount,sent
id1,name1,email1,1234.56,
id2,name2,email2,1234.56,