Python_Beginer/Study
Python Open - With as
AnKiWoong
2019. 4. 25. 15:50
반응형
Open with as 기본 사용법>
with open('파일명', 'r', encoding='인코딩 방식') as file:
file = file.read()
print(file)
1. Open with as
파일을 읽고 쓰고 할 때마다 매번 아래와 같은 명령어를 사용했다.
file.close()
하지만 이 문구를 사용하지 않고 자동으로 할 수 있는 것이 open에 with as 함수이다.
1-1. Code>
with open('i love python.txt', 'r', encoding='utf-8') as file:
file = file.read()
print(file)
1-1 Code 출력물>
Hello, world!
Welcome to Python!!
Hello
Process finished with exit code 0
2. with as 'w'
Code>
with open("i love python2.txt", "w", encoding='utf-8') as file:
for i in range(0, 10):
file.write("%d ) " % i)
file.write("python\n")
출력물>
for 문을 활용하면 위와 같은 출력물을 만들 수 있다.
기존과 다른점은 역시 file.close()를 사용하지 않아도 정상적으로 작동한다는 것이다.
반응형