Python_28_ with

hyeong taek jo·2023년 9월 13일

Python

목록 보기
32/53

📌 with

  • with < expression> as < variable>:
  • with의 expression에서 해당 구문에서 어떤 작업을 할 건지 작성하고 해당 작업이 어떤 변수인지는 as에서 체크를 해준다.
  • 해당 경우에서 주어진 실행문이 끝나면 자동으로 close를 하고 구문이 종료가 된다.
  • 예를들어 open을 그냥 사용하면 close를 해줘야 하는데 with를 쓰면 안해줘도 된다.

📌 예시

with open('test3.txt','r',encoding='UTF8') as file:
    str = file.readlines()
    for s in str:
        print(s, end='')

hello
안녕하세요

profile
마포구 주민

0개의 댓글