본문 바로가기
  •                        自分に負けずやれば出来る
  • 自分を信じる
Computer/Programming Language

pickle 간단 사용법 feat. with문

by Divertome 2021. 2. 18.
import pickle

profile_file=open("profile.pickle","wb") #wb:write binary라는 뜻
profile={"이름":"박명수", "나이":30, "취미":["축구","유튜브 촬영":"코딩"]}
print(profile)
pickle.dump(profile,profile_file) #profile에 있는 정보를 file에 저장
profile_file.close()

profile_file=open("profile.pickle","rb") #rb:read binary라는 뜻
profile=pickle.load(profile_file)#file에 있는 정보  불러오기
print(profile)
profile_file.close()


#with 문을 사용하게 된다면 훨씬 더 간단하게 표현가능하다.

with open("profile.pickle","rb") as profile_file:
    print(pickle.load(profile_file))

#profile_file.close()없이도 파일 자동 종료



with open("study.txt","w", encoding="utf8") as study_file:
    study_file.write("파이썬을 공부중입니다.")

with open("study.txt","r", encoding="utf8") as study_file:
    print(study_file.read())



#둘다 모두 with문이 끝날 경우 자동으로 파일 open을 종료한다.

단순히 파일 저장과 차이점이 뭘까?