파이썬/파이썬(python) 중급

[24-2 파이썬] 파일 모드(w, r, a), 없는 파일 생성하기, with as 키워드

Olivia-BlackCherry 2022. 9. 3. 10:33

파이썬 with 키워드를 배운다.

오늘 배운 기능을 이용하면

이제 더이상 마우스를 사용하지 않고도

파일을 열고 닫을 수 있을 것이다.

 

open()

파일을 연다.

open("파일명")

 

mode: "r", "w", "a"

열린 파일을 어떻게 처리할 것인지를 정해준다.

디폴트 값은 r이다.

mode 의미
r 읽기
w 덮어쓰기(이전 파일 내용 삭제)
a 이어쓰기

 

 

read()

mode: "r"

파일을 읽는다.

 

english_my_file.txt

Hello! Nice to see u!
Fingers crossed and good luck to you.
Anywhere, anytime. I will always pray for you!
From Olivia.

위 파일을 열고, 읽는다.

 

file = open("english_my_file.txt", mode="r")
contents = file.read()
print(contents)

 

 

write()

mode: "w"

위 파일에 "Oops!!"를 덮어 쓴다.

덮어 쓴다의 개념은,

그 전에 쓴 내용은 모두 지워진다는 것이다.

file = open("english_my_file.txt", mode="w")
file.write("Oops!!")
file.close()

enlish_my_file.txt  

이전에 썼던 내용이 모두 삭제되었다.....

(당황..)

 

mode: "a"

기존의 파일에 단지 추가만 하고 싶다면 a모드를 사용한다.

a는 append(덧붙이다)의 첫 글자이다.

Oops!!를 삭제하지 않고,

브리트니 스피어스의 Oops, I did it again 가사를 이어 붙여 보겠다.

file = open("english_my_file.txt", mode="a")
file.write(
'''I did it again
I played with your heart, got lost in the game
Oh baby, baby
Oops, you think I'm in love
That I'm sent from above
I'm not that innocent
''')
file.close()

 


지금 자신의 인터넷 브라우저에 탭이 몇 개나 열어져 있는지 확인해보자!

올리비아 같은 경우는 5개가 열려 있다!

 

여러 개의 탭을 두고 쓰면, 편리하기는 하나

컴퓨터 속도가 떨어지는 것을 느낄 수 있다.

 

파일을 계속 열어두면, 컴퓨터의 CPU와 리소스를 계속 사용하게 되는데

이것은 비효율적이다. 

 

컴퓨터가 최고의 성능을 발휘하기 위해서는, 

사용하지 않는 파일은 닫아주는 것이 좋다.

 

파일을 닫을 때 사용하는 함수이다.

 

 

 

close()

파일을 닫는다.

file.close()

 

그런데, 파일을 열고 나서 

바로 닫는 것이 아니고, 

 

그 중간에 무수한 과정들이 있기 때문에

파일을 닫는 것을 깜빡하는 경우가 많다. 

 

그래서 쓰이는 것이 

with 키워드이다.

 

 

 

with 파일열기 as 파일이름정하기 :

with키워드가 파일을 직접 관리하기 때문인데

자기가 할 일을 끝내면 즉시 파일을 닫아버린다.

즉 with키워드를 쓰면, 수동으로 파일을 닫을 필요가 없다.

with open("english_my_file.txt") as file:
    contents = file.read()
    print(contents)
with open("english_my_file.txt", mode="w") as file:
    file.write("Oops!!")
with open("english_my_file.txt", mode="a") as file:
    file.write(
    '''I did it again
    I played with your heart, got lost in the game
    Oh baby, baby
    Oops, you think I'm in love
    That I'm sent from above
    I'm not that innocent
    ''')

 

 

파일생성하기

그런데 만약 해당 파일이 존재하지 않는다면 어떻게 될까?

쓰기 모드(mode="w")인 경우에는

고맙게도

컴퓨터가 실제 그 파일을 만들어준다.

with open("thank_you.txt", mode="w") as file:
    file.write("To computer. Thank you for making new file for me.")