개발/ETC

[python]엄청 큰 csv파일 읽기

wonpick 2021. 5. 10. 12:35

맨날 메모리 부족

error_bad_lines : bool,
너무 많은 필드가있는 기본 True Line (예 : 너무 많은 쉼표가있는 csv 라인)은 기본적으로 예외를 발생시키고 DataFrame이 반환되지 않습니다. False이면 반환되는 DataFrame에서 이러한 "불량 행"이 삭제됩니다.
warn_bad_lines : bool, 기본값 True,
error_bad_lines가 False이고 warn_bad_lines가 True이면 각 "불량 라인"에 대한 경고가 출력됩니다.

## chunk size를 달리하여 2개를 돌림 아래는 100. 100 & 10000

## 시도1

import pandas as pd


def do_processing(data):
    indexs = data.index.values
    print(len(indexs))

filename = (r"path")
for chunk in pd.read_csv(filename,error_bad_lines=False,encoding='utf-16',sep=';',chunksize=100000):
    do_processing(chunk)

chunk size가 다를 때 아래와 같은 오류가 발생하는 행 수가 다르다.
이유는 나중에 더 자세히 알아봐야겠다

+알고 보니 내가 구분자를 명시안해줘서 발생하는 오류였다. (파일 저장할 때 ';'를 기준으로 구분했기 때문에 명시 필요)

# 구분자 명시로 해결!
🚨b'Skipping line 1488395: expected 14 fields, saw 15\n'🚨 

참고1
참고2

# -*- coding: cp949-*- 
import os

nDivCnt = 20000

#파일 경로
filepath = (r"C:/Users/user/Documents/")
#변경할 파일
fileName ='파일명'
#변경할 파일 확장자
fileExe ='.csv'

#나눈 파일을 만들 폴더
fileFolder = 'div/'

#디렉토리가 없으면 생성
dirname = filepath + fileFolder
if not os.path.isdir(dirname):
    os.mkdir(dirname)

nLineCnt = 0
nFileldx = 0

f = open ("%s" % (filepath + fileName+fileExe), 'r')
fDivName = open ("%s%06d%s" % (filepath + fileFolder + fileName, nFileldx, fileExe), 'w')
while True:
    line = f.readline()
    if not line:
        break

    if nLineCnt == nDivCnt:
            fDivName.close()
            nFileldx +=1
            nLineCnt = 0
            strPat = "%s%06d%s" % (filepath + fileFolder + fileName, nFileldx, fileExe)
            fDivName = open(strPat, 'w')
            print("생성 완료 %s" % strPat)
    nLineCnt +=1
    fDivName.write(line)

fDivName.close()
f.close()