AboutPython

[파이썬] with ~ as문

scone 2022. 5. 10. 01:59

[with ~ as문]

  • 파일 닫기를 생략할 수 있다.
  • 기존에 우리는 이렇게 했었다.
from url import *

file = open(url()+'practice03.txt','w')
file.write('let\' practice with ~ as ~')
file.close()

 

  • with ~ as ~ 를 쓰면 코드가 다음과 같아진다.
with open(url()+'practice03.txt','a') as f:
    f.write('\nthis is the with ~ as 구문')

with open(url()+'practice03.txt','r') as f :
    print(f.read())
'''
let' practice with ~ as ~
this is the with ~ as 구문
'''

close()를 쓰지 않아도 알아서 close()를 실행하여 괜찮다는것을 볼 수 있다.

 

  • 자칫하여 close()를 깜빡했다가는 프로그래밍할 때 심각한 오류를 초래할 수도 있으므로, with as 구문을 쓰는 것이 권장사항이라고 한다.

[실습] 로또 번호를 추첨해주는 텍스트 파일을 만들어보자. 

from url import *
import random

def lotto(randN):
    with open(url()+'로또추천.txt','a') as f:
        for idx, i in enumerate(randN):
            if idx == 0 :
                f.write(f'{i}')
            elif idx == len(randN)-1:
                f.write(f'\nBonus : {i}')
            else :
                f.write(f', {i}')
randomNumbers = random.sample(range(1,46),7)
print(randomNumbers)
lotto(randomNumbers)
'''
[29, 20, 34, 30, 26, 23, 32]
'''

실행 한번 돌릴 때마다 잘 된다.