카테고리 없음

파이썬 데이터 입출력 with open()

개발자국S2 2021. 12. 6. 19:23

https://onlytojay.medium.com/%ED%8C%8C%EC%9D%B4%EC%8D%AC-open-file-1e1adcb0f219

 

파이썬, open file

파일 열기 기본

onlytojay.medium.com

 

내가 필요했던 정보들

**는 내 의견,, 

 

close 대신 with

어쨌든 이 f.close()매번 해주는 것도 귀찮으므로 대안으로 with 를 사용할 수 있다.

with open(filename) as f:
    print('Closed inside with?:', f.closed)
print('Closed outside with?:', f.closed)# Closed inside with?: False
# Closed outside with?: True

 

 

f의 정체는?

with open(filename) as f:
    print(f)
    print(type(f))# <_io.TextIOWrapper name='C:\\Users\\jay\\Desktop\\test.txt' mode='r' encoding='cp949'>
# <class '_io.TextIOWrapper'>

일단 f는 파이썬의 내장io 모듈의 _io.TextIOWrapper 클래스로 만들어진 instance 인 것을 알 수 있다.

**뭐 하지만 그냥 레퍼런스 변수정도로 이해해도 될것같은데..

 

str타입과 byte타입

with open(filename,"r") as f:
    x = f.read()
    print(type(x))# <class 'str'>

'r'모드로 읽힌 것은 str 타입으로 반환된다.

 

**습관적으로 파일을 'r'로 읽어왔는데, r이 string을 반환한다는 걸 지금 알았다!

반응형