수색…


통사론

  • pickle.dump (obj, file, protocol = None, *, fix_imports = True)

  • pickle.load (file, *, fix_imports = True, encoding = "ASCII", errors = "strict")

매개 변수

매개 변수 세부
obj 열린 파일 객체 파일에 대한 obj 표현
실험 계획안 정수, pickler에게 주어진 프로토콜, 0 -ASCII, 1 오래된 바이너리 형식을 사용하도록 지시한다.
파일 file 인수는 덤프 메소드와 read () 메소드를로드하기위한 write () 메소드 wb 를 가져야합니다. rb

파이썬 지속성

숫자, 목록, 사전, 중첩 구조 및 클래스 인스턴스 객체와 같은 객체는 컴퓨터의 메모리에 저장되며 스크립트가 종료 되 자마자 손실됩니다.

pickle은 데이터를 별도의 파일에 지속적으로 저장합니다.

피클 링 된 객체 표현은 항상 모든 경우에 바이트 객체이므로 데이터를 저장하려면 wb 로 파일을 열고 pickle에서 데이터를로드하려면 rb 를 열어야합니다.

데이터는 모든 종류의 데이터 일 수 있습니다. 예를 들어,

data={'a':'some_value',
     'b':[9,4,7],
     'c':['some_str','another_str','spam','ham'],
     'd':{'key':'nested_dictionary'},
     } 

데이터 저장

import pickle
file=open('filename','wb')  #file object in binary write mode
pickle.dump(data,file)      #dump the data in the file object
file.close()                #close the file to write into the file

데이터로드

import pickle
file=open('filename','rb')  #file object in binary read mode
data=pickle.load(file)      #load the data back
file.close()

>>>data
{'b': [9, 4, 7], 'a': 'some_value', 'd': {'key': 'nested_dictionary'},
 'c': ['some_str', 'another_str', 'spam', 'ham']}

다음 유형의 절임이 가능합니다.

  1. 없음, 참 및 거짓
  2. 정수, 부동 소수점 수, 복소수
  3. 문자열, 바이트, bytearrays
  4. pickable 객체 만 포함하는 튜플, 목록, 세트 및 사전
  5. 모듈의 최상위 레벨에서 정의 된 함수 (람다가 아닌 def 사용)
  6. 모듈의 최상위 레벨에서 정의 된 내장 함수
  7. 모듈의 최상위 레벨에 정의 된 클래스
  8. dict 또는 getstate () 호출 결과와 같은 클래스의 인스턴스

저장 및로드를위한 함수 유틸리티

파일간에 데이터 저장

import pickle
def save(filename,object):
    file=open(filename,'wb')
    pickle.dump(object,file)
    file.close()

def load(filename):
    file=open(filename,'rb')
    object=pickle.load(file)
    file.close()
    return object


>>>list_object=[1,1,2,3,5,8,'a','e','i','o','u']
>>>save(list_file,list_object)
>>>new_list=load(list_file)
>>>new_list
[1, 1, 2, 3, 5, 8, 'a', 'e', 'i', 'o', 'u'


Modified text is an extract of the original Stack Overflow Documentation
아래 라이선스 CC BY-SA 3.0
와 제휴하지 않음 Stack Overflow