open('파일명','모드')
함수를 사용한다.# python 2.5 from __future__ import with_statement with open("hello.txt") as f: for line in f: print line # In older versions of Python, you would have needed to do this to get the same effect: f = open("hello.txt") try: for line in f: print line finally: f.close()
codecs 모듈을 사용해서 파일을 열면 내용을 Unicode로 읽어들인다.
import codecs f = codecs.open('파일명', encoding='utf-8') for line in f: print repr(line)
쓰기시에는 unicode 객체를 저장해야 한다.
f = codecs.open('test', encoding='utf-8', mode='w+') f.write(u'\u4500 blah blah blah\n')