Python 에서 CSV 파일 open 시 유니코드 에러를 Try, Except 문으로 접근할때 생기는 에러

조회수 3033회

이전 질문에서 조금 더 보완하여 다시 올립니다. 지정한 폴더에서 CSV 파일들을 읽어와 컬럼들을 새로운 CSV 파일에 작성하는 코드입니다. 파일들에 대하여 try 로 열고 오류가 나면 exceptutf-8 읽기를 해보려고 합니다.

import csv
import glob
import os
lst=[]
files=glob.glob('C:/dataset/*.csv')
with open('test2.csv','w',encoding='cp949',newline='') as testfile:
    csv_writer=csv.writer(testfile)
    for file in files:
        try:
            with open(file,'r') as infile:
                file=file[file.rfind('\\')+1:]
                reader=csv.reader(infile)
                headers=next(reader) 
                headers=[str for str in headers if str] 
                while len(headers) < 3 :
                    headers=next(reader) 
                    headers=[str for str in headers if str]
                lst=[file]+headers
                csv_writer.writerow(lst)
        except:
             with open(file,'r',encoding='utf8') as infile:
                file=file[file.rfind('\\')+1:]
                reader=csv.reader(infile)
                headers=next(reader)
                headers=[str for str in headers if str]
                while len(headers) < 3 :
                    headers=next(reader) 
                    headers=[str for str in headers if str]
                lst=[file]+headers
                csv_writer.writerow(lst)

그 결과 다음과 같은 에러가 발생합니다.

Traceback (most recent call last):
  File "C:\Python35\2.py", line 15, in <module>
    headers=next(reader)
UnicodeDecodeError: 'cp949' codec can't decode byte 0xec in position 6: illegal multibyte sequence

During handling of the above exception, another exception occurred:

Traceback (most recent call last):
  File "C:\Python35\2.py", line 23, in <module>
    with open(file,'r',encoding='utf8') as infile:
FileNotFoundError: [Errno 2] No such file or directory: '2010년1월기준.csv'

Try 에서 열어서 오류가 있다고 판단한 파일을 except에서 못 찾는게 Try에서 열린 파일이 닫기지 않아서 그런건가요? With 문을 사용하면 상관이 없는 걸로 아는데 왜 위와 같은 오류가 생길까요

2 답변

답변을 하려면 로그인이 필요합니다.

프로그래머스 커뮤니티는 개발자들을 위한 Q&A 서비스입니다. 로그인해야 답변을 작성하실 수 있습니다.

(ಠ_ಠ)
(ಠ‿ಠ)