python 파일에 문자열 쓰기, 읽기, 문자열에 여러 줄 파일 쓰기, 읽기, 개체 파일에 저장하기, 가져오기

yo·2020년 5월 11일
0


file = open() #파일열기
file.write() #파일쓰기
file.close() #파일닫기


반복문으로 문자열 여러 줄 파일에 쓰기






파이썬 객체를 파일에 저장, 가져오기

-파이썬은 객체를 파일에 저장하는 pickle 모듈을 제공.
-피클링(pickling): 파이썬 객체를 파일에 저장하는 과정
-언피클링(unpickling): 파일에서 객체를 읽어오는 과정

how to pickle

import pickle

name = 'james'
age = 17
adress = '서울시 영등포구'
scores = {'english': 90, 'math' : 100, 'science': 95}

with open('james.p', 'wb') as file:
    pickle.dump(name, file)
    pickle.dump(age, file)
    pickle.dump(adress, file)
    pickle.dump(scores, file)

-위 코드 실행 시 .py파일이 있는 폴더에 james.p파일 생성됨
-확장자를 pickle의 p로 했지만, 다른 확장자 써도 무관.
-pickle.dump로 객체(값)를 저장할 때는 open('james.p', 'wb')과 같이 파일 모드를 'wb'로 지정해야 됨
-b는 binary, 컴퓨터가 처리하는 파일 형식.
-메모장으로 열어도 사람이 알아보기 어려움
-.txt파일은 사람이 알아보기 쉽도록 만든 파일형식이고 text파일이라 부름.

how to unpickling

import pickle

with open('james.p', 'rb') as file:
    name = pickle.load(file)
    age = pickle.load(file)
    address = pickle.load(file)
    scores = pickle.load(file)
    print(name)
    print(age)
    print(address)
    print(scores)

결과

james
17
서울시 영등포구
{'english': 90, 'math': 100, 'science': 95}

-unpickling도 pickling과 마찬가지로 pickle.load 4번 사용해야 됨.
-name, age, address, scores순으로 저장했으므로 언피클링시 같은 순서로 하면 됨.

profile
Never stop asking why

0개의 댓글