sm 기술 블로그

13. 파일 입출력 / pickle / with 본문

Python

13. 파일 입출력 / pickle / with

sm_hope 2022. 5. 5. 19:52

 

score_file = open("score.txt","w",encoding ="utf8")

# score 파일을 W (Write) 쓴다. utf8 <-- 한글 깨지는 것을 방지하기 위함.

print("수학 : 0", file=score_file)
print("영어 : 50", file=score_file)
score_file.close()

# 텍스트 파일이 생성됨




score_file = open("score.txt","a",encoding ="utf8")

# score 파일을 a 이어쓴다.

score_file.write("\n코딩 : 100")
score_file.close()




score_file = open("score.txt","r",encoding ="utf8")

# score 파일을 r (read) 읽는다.

print(score_file.read())  # 한번에 읽음
print(score_file.readline(), end="")  # 한 줄씩 읽음

# 몇줄 인지 모를 때 반복문으로 읽을 수 있다.
while True:
     line = score_file.readline()
     if not line:
         break
     print(line, end="") #줄 바꿈 하기 싫을때 end 사용

score_file.close()




score_file = open("score.txt","r",encoding ="utf8")
lines = score_file.readlines() #list 형태로 저장 
							   #readlines()면 전부다 readline()면 한줄씩
for line in lines:
    print(line, end="")
    # 한줄 씩 출력 위 반복문과 결과는 똑같다.

score_file.close()

 

 

# 출력 결과
수학 : 0
영어 : 50
코딩 : 100



수학 : 0
영어 : 50
코딩 : 100


수학 : 0
영어 : 50
코딩 : 100


수학 : 0
영어 : 50
코딩 : 100

pickle
파이썬 프로그램 상에서 사용하고 있는 데이터를 파일 형태로 저장하는것

pickle은 바이너리 형태로 저장되기 때문에 불러올 때 속도가 빠르다.

 

(1) 파일 쓰기

import pickle
profile_file = open("profile.pickle","wb") #b는 binary pickle을 쓰기위해 필요
profile = {"이름" : "박명수", "나이":30, "취미":["축구","골프","코딩"]}
print(profile)
pickle.dump(profile, profile_file) #profile에 있는 정보를 file에 저장
profile_file.close()

pickle을 사용하기 위해서는 import를 해줘야한다.

 

dump를 통해 파일을 저장한다.

 

 

 

(2) 파일 읽기

profile_file = open("profile.pickle","rb") #읽기
profile = pickle.load(profile_file) #file에 있는 정보를 profile에 불러오기
print(profile)
profile_file.close()

load 를 통해서 파일을 불러온다.

 


with
코드를 더 깔끔하고 읽기 쉽게 만들기 위해, 예외 처리를 위해 사용

(1) 생성후 읽기

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 을 통해 코드를 간단히 작성할 수 있다.

 

 

(2) pickle, with 함께 사용

import pickle

with open("profile.pickle","rb") as profile_file:
    print(pickle.load(profile_file))
    #profile_file에 pickle파일을 저장함
    #close를 안해줘도 된다.

 

 

 

Comments