본문 바로가기

Python_Beginer/Study

Python Open - With as

반응형

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()를 사용하지 않아도 정상적으로 작동한다는 것이다.

반응형

'Python_Beginer > Study' 카테고리의 다른 글

Python Pickling / Unpickling  (0) 2019.04.26
Python Open - writelines / readlines / readline  (0) 2019.04.25
Python Open - w / r / a  (0) 2019.04.25
Pycharm 한글 에러 발생 해결 방안  (0) 2019.04.24
Python Operator(연산자)  (1) 2019.04.23