반응형

csv writerow 사용시  file open mode 설정주의


환경 : windows 7 32bit, python 2.7.7   



**  csv 모듈에서 , writerow 사용시 , file open mode를 text mode ('w') 로만 open시에는  

newline 으로 '\r\n' 대신에 '\r\r\n'이 들어가서 문제발생의 가능성 유발한다.

(하지만, ubuntu 12.04 LTS 환경에서는 text mode로 open 해도 정상적으로 입력됨)


import csv

with open('monty_python.csv','w') as f:    # mode = 'w'
    cfw = csv.writer(f, dialect = 'excel')
    cfw.writerow(['spam','spam','eggs','spam'])
    cfw.writerow(['spam','spam','spam and eggs','spam'])
    cfw.writerow(['toast'])


with open('monty_python.csv','rb') as f:
    for line in f:
        print repr(line)








*** 해결책 

    --- file open 시에 binary mode로 open 하면됨. ('wb')


import csv

with open('monty_python.csv','wb') as f:     # mode = 'wb'
    cfw = csv.writer(f, dialect = 'excel')
    cfw.writerow(['spam','spam','eggs','spam'])
    cfw.writerow(['spam','spam','spam and eggs','spam'])
    cfw.writerow(['toast'])


with open('monty_python.csv','rb') as f:
    for line in f:
        print repr(line)










반응형
Posted by 자유프로그램
,