본문 바로가기
파이썬

파이썬 _csv.Error : 반복자는 바이트가 아닌 문자열을 반환해야합니다 (텍스트 모드에서 파일을 열었습니까?).

by º기록 2020. 12. 21.
반응형

내 csv 프로그램을 시작할 때 :

import csv     # imports the csv module
import sys      # imports the sys module

f = open('Address Book.csv', 'rb') # opens the csv file
try:
    reader = csv.reader(f)  # creates the reader object
    for row in reader:   # iterates the rows of the file in orders
        print (row)    # prints each row
finally:
    f.close()      # closing

그리고 오류는 다음과 같습니다.

    for row in reader:   # iterates the rows of the file in orders
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)

 

해결 방법

 

이것 (및 나머지) 대신 :

f = open('Address Book.csv', 'rb')

이 작업을 수행:

with open('Address Book.csv', 'r') as f:
    reader = csv.reader(f) 
    for row in reader:
        print(row)  

컨텍스트 관리자는 finally : f.close () 가 필요하지 않음을 의미합니다. 오류가 발생하거나 컨텍스트를 종료 할 때 파일을 자동으로 닫기 때문입니다.

 

참조 페이지 https://stackoverflow.com/questions/22132034

 

 

반응형

댓글