有人能告诉我为什么在python3上收到以下错误。以下是回溯:
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'
以下是源代码:
^{pr2}$
错误似乎来自于使用Python3,但使用Python2要求打开
csv
文件。如果使用python3,CSV文件不应该以二进制模式打开,newline参数应该是空字符串。临时文件也默认为二进制模式,所以我重写了它。我还将下面的代码用作输入文件,因为没有提供示例输入,所以从代码中推导出来。在appendpyt2.csv:
Python3代码:
^{pr2}$临时文件输出:
相关问题 更多 >
编程相关推荐