python3 CSV TypeError ValueError _csv.Error

时间:2016-12-22 13:13:26

标签: python-3.x

我跟随Udemy的一个学习项目叫做 " 30天的Python |解锁你的Python潜力" 这是第16天的事情。

这是我的代码

filename = "data.csv"
temp_file = NamedTemporaryFile(delete=False)

with open(filename, "rb") as csvfile, temp_file:
    reader = csv.DictReader(csvfile)
    fieldnames = ["id", "name", "email", "amount", "sent"]
    writer = csv.DictWriter(temp_file, fieldnames=fieldnames)
    #writer.writeheader()


for row in reader:
    print(row)
    writer.writerow({
            "id": row["id"],
            "name": row["name"],
            "email": row["email"],
            "amount": "1293.23",
            "sent": ""
        })

虽然我检查了我的代码与教师代码

相同但我收到了错误消息
Traceback (most recent call last):
  File "hungry_data.py", line 36, in <module>
    for row in reader:
  File "C:\Users\Another\AppData\Local\Programs\Python\Python35-32\lib\csv.py", line 109, in __next__
    self.fieldnames
  File "C:\Users\Another\AppData\Local\Programs\Python\Python35-32\lib\csv.py", line 96, in fieldnames
    self._fieldnames = next(self.reader)
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

因此我更改了#34; rb&#34;到&#34; r&#34; .... with open(filename, "r") as csvfile, temp_file:

也是这样

with open(filename, "r", newline='') as csvfile, temp_file:

但是得到同样的错误

Traceback (most recent call last):
  File "hungry_data.py", line 43, in <module>
    "sent": ""
  File "C:\Users\Another\AppData\Local\Programs\Python\Python35-32\lib\csv.py", line 153, in writerow
    return self.writer.writerow(self._dict_to_list(rowdict))
  File "C:\Users\Another\AppData\Local\Programs\Python\Python35-32\lib\tempfile.py", line 483, in func_wrapper
    return func(*args, **kwargs)
TypeError: a bytes-like object is required, not 'str'

似乎线36与线43发生冲突 我该怎么做......

1 个答案:

答案 0 :(得分:0)

您应该尝试以写入模式打开文件。

with open(filename, "w")

引发异常导致U尝试写入仅为读取而打开的文件,如果要从文件使用中读取和写入

with open(filename, "+")

source python doc

此外,您的例外可能会被提出,因为您在“rb&#39;模式,其中b是以字节为单位读取的。尝试从模式中删除b