티스토리 뷰

Daylogs/Python

File open modes

ohgyun 2012. 10. 31. 00:46


발생일: 2012.10.31

문제:
지난 주부터 파이썬 스터디를 하고 있는데,
오늘은 아주 간단한 파일 처리 코드를 익혔다.

파일을 열 때 파일 모드를 파라미터로 넣는데,
파일 모드는 정말 봐도 까먹고 봐도 까먹고 한다.

조금 헷갈리는 것도 있어서, 
이번에 정확하게 정리해두려고 한다.

해결책:
파이썬의 내장 opne() 함수의 파일 오픈 모드는, C의 fopen()과 정확하게 일치한다.
파일 모드에 관한 정의는 BSD fopen 매뉴얼 페이지에 정확하게 설명되어 있다.

각 파일 모드가 어떤 작업을 하는지, 파일을 열었을 때 커서가 어디에 있는지
정확하게 알아두자.

``r''   Open text file for reading.  The stream is positioned at the
             beginning of the file.

     ``r+''  Open for reading and writing.  The stream is positioned at the
             beginning of the file.

     ``w''   Truncate to zero length or create text file for writing.  The
             stream is positioned at the beginning of the file.

     ``w+''  Open for reading and writing.  The file is created if it does not
             exist, otherwise it is truncated.  The stream is positioned at
             the beginning of the file.

     ``a''   Open for writing.  The file is created if it does not exist.  The
             stream is positioned at the end of the file.  Subsequent writes
             to the file will always end up at the then current end of file,
             irrespective of any intervening fseek(3) or similar.

     ``a+''  Open for reading and writing.  The file is created if it does not
             exist.  The stream is positioned at the end of the file.  Subse-
             quent writes to the file will always end up at the then current
             end of file, irrespective of any intervening fseek(3) or similar.


목적에 따라 파일 모드를 정리해보면...

파일을 읽으려면: r, r+, w+, a+
파일을 쓰려면: r+, w, w+, a, a+
없는 파일을 생성하려면: w, w+, a, a+
파일을 덧붙이는데,
앞쪽에 붙이려면: r+,
뒷쪽에 붙이려면: a, a+
파일을 덮어쓰려면: w, w+ 


정리하고나니 별 거 없는데, 왜이리 헷갈렸던 걸까.. -_-
여튼, 이제 안 까먹겠다. ㅎㅎㅎ



반응형
댓글
공지사항