사용자 도구

사이트 도구


python:file

문서의 이전 판입니다!


Python File 다루기

파일 열어 줄 읽기

# 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()

Unicode File

읽기

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')
python/file.1343785442.txt.gz · 마지막으로 수정됨: 2012/08/01 10:44 저자 kwon37xi