8.6 파일 한번에 열고 닫기 : with문
open()함수를 이용하여 파일을 열었을 경우 반드시 close()함수로 닫아야 한다.
with문은 파일을 열고 나서 close()함수를 호출하지 않아도 자동으로 닫아 주는 역할을 함
형식 with 작업 as 변수명:
실행할 명령1
실행할 명령2
....
- 들여쓰기 규칙 지키기, 변수명 끝에 콜론(:),
<실습>
import pickle
with open("profile.pickle","rb") as profile_file:
print(pickle.load(profle_file))
실행결과
study.txt 라는 파일을 쓰기모드로 열고 encoding은 utf8로 지정. study_file이라는 이름의 변수에 담기
다음줄에서 write()함수로 파일에 쓸 내용을 작성
import pickle
with open("study.txt","w",encoding="utf8") as study_file:
study_file.wirte("파이썬을 열심히 공부하고 있어요.")
실행하면 study.txt파일이 생성됨
읽기모드인 r을 이용하여 열어보기
import pickle
with open("study.txt","r",encoding="utf8") as study_file:
print(study_file.read())
실행결과
파이썬을 열심히 공부하고 있어요
with를 쓰면 파일을 읽고 쓰기가 간결해짐
#1분 퀴즈
with를 사용해 파일을 열기 위한 문법으로 올바른 것은?
(단, open()함수에 들어가는 값은 편의상.... 로 대체한다)
1. f = with open(....)
2. with f = open(...)
3. open(...) as f with:
4. with open(...) as f:
정답 : 4