본문 바로가기
코딩(개발)

파이썬 pickle / with

by 플랜데버 2020. 12. 20.

공부하는게 취미인 사람들 투딩


#pickle : 데이터를 파일로 만들어 주는 것

코드
import pickle
profile_file = open("profile.pickle" , "wb")  ①
profile = {"이름":"박명수","나이":30, "취미":["축구","골프","코딩"]}
print(profile_file)
pickle.dump(profile,profile_file)  ②
profile_file.close()

파일명 , 쓰기목적으로 binary 타입을 정의, encoding 은 정하지 않아도 된다.

profile 에 있는 정보를 file에 저장

 

 

#pickle 에 있는 파일 읽기

코드
import pickle
profile_file = open("profile.pickle" , "rb") ①
profile = pickle.load(profile_file)  ②
print(profile)
profile_file.close()


* with 를 이용해 더 간단하게 읽어올수 있다.
with open("profile.pickle","rb") as profile_file:
    print(pickle.load(profile_file))   #close 할 필요 없이 간편하게 할수 있다.


파일명 , 읽기 목적으로 binary 타입을 정의, encoding 은 정하지 않아도 된다.

 파일에 있는 정보를 profile에 불러오기

 

 

 

※ with 

:좀더 편하게 pickle 쓴것과 동일하게 할 수 있다.

 

# with 를 이용한 파일 쓰기

코드

import pickle
with open("study.txt" , "w" , encoding="utf-8"as study_file:
    study_file.write ("파이썬을 열심히 공부하고 있어요")

 

# with 를 이용한 파일 읽기

코드

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

 

 

 

더보기

블로그에는 우클릭 방지가 걸려있어요. 코드복사는 카페에서 가능 합니다.

투딩카페의 이 컨텐츠보기

 

 

중간중간 제 생각이 첨삭된 부분이 있습니다. 실제 강의는 선생님걸로 들으세요~

파이썬 기초는 나도코딩님이 인프런사이트에서 강의한 내용을 바탕으로 공부한 내용을 정리한 것 입니다.


추천 :  ★

 

목소리 : 

속도 :

내용 : 

결과물 :

 

'코딩(개발)' 카테고리의 다른 글

vscode 에서 spring boot 테스트 코드 자동 생성  (0) 2023.01.08

댓글