0
有人能告訴我爲什麼會收到有關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": ""
})
似乎PROBL em打開文件爲'rb'。請提供堆棧跟蹤到隊列 – ShmulikA
你能顯示實際的回溯?順便說一句,這不是[最小的,可驗證的例子](https://stackoverflow.com/help/mcve)。它確實有助於你提供一個。 – jszakmeister
你用2.7和3-x標記了這個。你在用哪個?這兩者之間的字符串編碼問題常常不同。 – hpaulj