1. 程式人生 > >csv.Error: iterator should return strings, not bytes

csv.Error: iterator should return strings, not bytes

python 讀取csv檔案問題

with open("fer2013.csv", "rb", encoding="utf-8") as vsvfile:
   reader = csv.reader(vsvfile)
   rows = [row for row in reader]
   print(rows)

輸出:

Error: iterator should return strings, not bytes (did you open the file in text mode?)

問題分析

因為此csv檔案並非二進位制檔案, 只是一個文字檔案。

問題解決

with
open("fer2013.csv", "rt", encoding="utf-8") as vsvfile: reader = csv.reader(vsvfile) rows = [row for row in reader] print(rows)

或者

# 因為open()預設開啟文字檔案
with open("fer2013.csv", "r", encoding="utf-8") as vsvfile:
   reader = csv.reader(vsvfile)
   rows = [row for row in reader]
   print(rows)