레이블이 line-by-line인 게시물을 표시합니다. 모든 게시물 표시
레이블이 line-by-line인 게시물을 표시합니다. 모든 게시물 표시

2017년 11월 26일 일요일

python, read txt line-by-line

list = open(FILENAME).read().splitlines()

만약 한글이 있어서,
UnicodeDecodeError: 'cp949' codec can't decode byte 0xa7 in position 55: illegal multibyte sequence
이라면, 다음으로 대체

import codecs
list = codecs.open(FILENAME, 'r', 'utf-8').read().splitlines()

그럼에도 아래와 같은 에러가 생긴다면
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xb0 in position
다음으로 대체

'utf-8' -> 'euc-kr'

2017년 9월 20일 수요일

python으로 list를 line-by-line으로 read와 write하자.

문제:
python으로 list를 line-by-line으로 read와 write하자.

해결:
def read_list_linebyline(fname):
    with open(fname) as fid:
        content = fid.readlines()
    content = [item.rstrip('\n') for item in content]

    return content


def write_list_linebyline(fname, thelist):
    fid = open(fname, 'w')

    for item in thelist:
        fid.write('%s\n' % (item))

    fid.close()