错误:迭代器应返回字符串,而不是字节

时间:2017-12-30 13:53:37

标签: python-3.x csv

我的代码抛出了这个错误:

    File "testdata.py", line 35, in <module>
      for row in reader:
    File "C:\Python36\lib\csv.py", line 111, in __next__
      self.fieldnames
    File "C:\Python36\lib\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?)

我按照这个tutorial完成了对视频的所有操作,并在此处查找了类似的问题,但到目前为止,我还没有找到解决问题的方法。

These are the files used in the video

此错误与this不同,我尝试使用该修复程序但是它导致了另一个错误。

我的代码:

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.33",
                "sent": "",
              })

1 个答案:

答案 0 :(得分:0)

import csv
from tempfile import NamedTemporaryFile

filename = "data.csv"
temp_file = NamedTemporaryFile(mode='w', delete=False)
with open(filename, "r", newline='') 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.33",
                "sent": "",
            })
  • mode='w'设置NamedTemporaryFile
  • mode='r'设为open以便阅读。
  • newline=''设为open以便阅读。

实现这些更改,它适用于我使用Python 3.6.0进行的测试。