오브젝트 저장(데이터 지속성)
다음과 같은 개체를 만들었습니다.
company1.name = 'banana'
company1.value = 40
이 오브젝트를 저장하고 싶습니다.내가 어떻게 그럴 수 있을까?
표준 라이브러리에서 모듈을 사용할 수 있습니다.예시에 대한 기본적인 적용 예를 다음에 제시하겠습니다.
import pickle
class Company(object):
def __init__(self, name, value):
self.name = name
self.value = value
with open('company_data.pkl', 'wb') as outp:
company1 = Company('banana', 40)
pickle.dump(company1, outp, pickle.HIGHEST_PROTOCOL)
company2 = Company('spam', 42)
pickle.dump(company2, outp, pickle.HIGHEST_PROTOCOL)
del company1
del company2
with open('company_data.pkl', 'rb') as inp:
company1 = pickle.load(inp)
print(company1.name) # -> banana
print(company1.value) # -> 40
company2 = pickle.load(inp)
print(company2.name) # -> spam
print(company2.value) # -> 42
파일을 열고 단일 개체를 쓰는 다음과 같은 자체 단순 유틸리티를 정의할 수도 있습니다.
def save_object(obj, filename):
with open(filename, 'wb') as outp: # Overwrites any existing file.
pickle.dump(obj, outp, pickle.HIGHEST_PROTOCOL)
# sample usage
save_object(company1, 'company1.pkl')
갱신하다
이것은 매우 인기 있는 대답이기 때문에, 조금 더 고도의 사용법에 대해 언급하고 싶습니다.
cPickle
(오류)_pickle
와 )의 비교pickle
대부분의 경우 모듈을 실제로 사용하는 것이 좋습니다.pickle
왜냐하면 전자는 C로 쓰여있고 훨씬 빠르기 때문이다.이들 사이에는 몇 가지 미묘한 차이가 있지만 대부분의 경우 동등하며 C 버전은 훨씬 뛰어난 성능을 제공합니다.수 없을 수 . 변경만 하면 됩니다.import
★★★★★★★★
import cPickle as pickle
3, Python 3의 경우cPickle
was was was was was was was was 、 was was was was 。_pickle
pickle
이제 module은 자동으로 실행됩니다. picle과 _pickle in python 3의 차이점은 무엇입니까?
결론은 다음과 같은 것을 사용하여 Python 2와 3 모두에서 사용 가능한 C 버전을 항상 사용할 수 있도록 하는 것입니다.
try:
import cPickle as pickle
except ModuleNotFoundError:
import pickle
데이터 스트림 형식(프로토콜)
pickle
는 설명서에 설명된 대로 프로토콜이라고 불리는 파이썬 고유의 여러 다른 형식의 파일을 읽고 쓸 수 있습니다. "프로토콜 버전 0"은 ASCII이므로 "사람이 읽을 수 있는" 형식입니다.버전 >0은 바이너리이며 사용 가능한 상위 버전은 사용 중인 Python 버전에 따라 달라집니다.기본값은 Python 버전에 따라 달라집니다.Python 2에서 기본값은 Protocol 버전입니다.0
3. version Python 3.8.1 Protocol이다.4
3.에는 Python 3.x가 되어 있습니다pickle.DEFAULT_PROTOCOL
파이썬2
운 좋게도 글을 쓰는 줄임말이 있다.pickle.HIGHEST_PROTOCOL
에는 그렇게 있습니다)에는의 번호인 '(그렇게 하면 됩니다)', '그렇게 하면 됩니다.-1
인덱스를 통해 하는 것과 합니다.- 네거티브 인덱스를 사용하여 마지막 요소를 참조합니다.다음 중 하나:
pickle.dump(obj, outp, pickle.HIGHEST_PROTOCOL)
다음과 같이 쓸 수 있습니다.
pickle.dump(obj, outp, -1)
쪽이든 간에 ''를 는 한 Pickler
「 」 「 」 、 「 」
pickler = pickle.Pickler(outp, -1)
pickler.dump(obj1)
pickler.dump(obj2)
etc...
주의: 다른 버전의 Python을 실행하고 있는 환경에서는, 모든 Python이 읽을 수 있는 특정의 프로토콜 번호(즉, 하드 코드)를 명시적으로 사용하고 싶은 경우가 있습니다(이후 버전은 일반적으로 이전 버전에서 생성된 파일을 읽을 수 있습니다).
다중 객체
위의 샘플에서 볼 수 있듯이 피클 파일은 임의의 수의 절임 개체를 포함할 수 있지만, 알 수 없는 수의 절임 파일이 있을 경우, 종종 그것들을 다양한 크기의 용기에 저장하는 것이 더 쉽습니다.list
,tuple
, 「」dict
호출로 에 쓸 수 있습니다.
tech_companies = [
Company('Apple', 114.18), Company('Google', 908.60), Company('Microsoft', 69.18)
]
save_object(tech_companies, 'tech_companies.pkl')
목록 및 목록 내의 모든 내용을 나중에 복원합니다.
with open('tech_companies.pkl', 'rb') as inp:
tech_companies = pickle.load(inp)
주요 장점은 나중에 로드하기 위해 몇 개의 오브젝트인스턴스를 저장해야 하는지 알 필요가 없다는 것입니다(다만, 이 정보는 없어도 가능하지만, 약간 특수한 코드가 필요합니다).피클 파일에 여러 개체를 저장하고 로드하시겠습니까? 관련 질문에 대한 답변을 참조하십시오.자세한 것은, 을 참조해 주세요.개인적으로 저는 @Lutz Prechelt의 답변이 가장 마음에 들었기 때문에 아래 샘플 코드에 사용된 접근법입니다.
class Company:
def __init__(self, name, value):
self.name = name
self.value = value
def pickle_loader(filename):
""" Deserialize a file of pickled objects. """
with open(filename, "rb") as f:
while True:
try:
yield pickle.load(f)
except EOFError:
break
print('Companies in pickle file:')
for company in pickle_loader('company_data.pkl'):
print(' name: {}, value: {}'.format(company.name, company.value))
이 '아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아, 아,아,class
약약게 a a a aclass
오브젝트가 인터프리터에서 정의되지 않았다는 가정도 있습니다.역에면면면면면면면면면?경우 Atribut은 어떻게 ?에 python 이 __dict__
후, 「 」pickle
의 추가를 은 '입니다. 왜냐하면 '예'가 아닌 '예'가 되다(예: '예'는 '예'입니다.pickle
는 오브젝트 정의에 따라 시리얼화됩니다).
「 」는, 「 」입니다.pickle
★★★★★★★★★★★★★★★★★」cPickle
당신을 끔찍하게 실망시킬 수 있어요
「」를 는, 「」를 해 주세요.object
로 작성)그 후에 에는 (오브젝트 정의에서 추가됨)를 하는 것이 dill
Python은 Python이라고 합니다.
수업부터 시작합시다.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>> with open('company.pkl', 'wb') as f:
... pickle.dump(company1, f, pickle.HIGHEST_PROTOCOL)
...
>>>
이제 종료하고 다시 시작합니다...
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import pickle
>>> with open('company.pkl', 'rb') as f:
... company1 = pickle.load(f)
...
Traceback (most recent call last):
File "<stdin>", line 2, in <module>
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1378, in load
return Unpickler(file).load()
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 858, in load
dispatch[key](self)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1090, in load_global
klass = self.find_class(module, name)
File "/opt/local/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/pickle.py", line 1126, in find_class
klass = getattr(mod, name)
AttributeError: 'module' object has no attribute 'Company'
>>>
이 oops...pickle
감당할 수 없어한번 해보지요dill
. 다른 오브젝트 타입을 입력합니다(a).lambda
를 참조해 주세요를 참조해 주세요.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> with open('company_dill.pkl', 'wb') as f:
... dill.dump(company1, f)
... dill.dump(company2, f)
...
>>>
그리고 이제 파일을 읽어보세요.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> with open('company_dill.pkl', 'rb') as f:
... company1 = dill.load(f)
... company2 = dill.load(f)
...
>>> company1
<__main__.Company instance at 0x107909128>
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>>
그건 효과가 있다. ★★pickle
실패하다dill
않아요??dill
__main__
수 예: 모럼대대대대대대대대대대대대 like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like like).pickle
입니다.dill
에 절일 수 lambda
이름이 붙여진다면 절임 마법이 일어날 수 있습니다.
실제로 이러한 모든 개체를 저장하는 더 쉬운 방법이 있습니다. 특히 만든 개체가 많은 경우에는 더욱 그렇습니다.비단뱀 세션 전체를 버리고 나중에 다시 와
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> class Company:
... pass
...
>>> company1 = Company()
>>> company1.name = 'banana'
>>> company1.value = 40
>>>
>>> company2 = lambda x:x
>>> company2.name = 'rhubarb'
>>> company2.value = 42
>>>
>>> dill.dump_session('dill.pkl')
>>>
이제 컴퓨터를 끄고 에스프레소나 뭐 그런 걸 즐기러 갔다가 나중에 다시 오세요.
Python 2.7.8 (default, Jul 13 2014, 02:29:54)
[GCC 4.2.1 Compatible Apple Clang 4.1 ((tags/Apple/clang-421.11.66))] on darwin
Type "help", "copyright", "credits" or "license" for more information.
>>> import dill
>>> dill.load_session('dill.pkl')
>>> company1.name
'banana'
>>> company1.value
40
>>> company2.name
'rhubarb'
>>> company2.value
42
>>> company2
<function <lambda> at 0x1065f2938>
유일한 큰 결점은 이다dill
비단뱀따라서 서버에 python 패키지를 설치할 수 없으면 사용할 수 없습니다.
할 수 python을 수 .dill
git+https://github.com/uqfoundation/dill.git@master#egg=dill
최신 할 수 pip install dill
.
「 」를 예:company1
python3는 python3를 나타냅니다.
import pickle
# Save the file
pickle.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = pickle.load(open("company1.pickle", "rb"))
그러나 이 답변에서 알 수 있듯이 피클은 종종 실패한다.그래서 꼭 사용하셔야 합니다.dill
.
import dill
# Save the file
dill.dump(company1, file = open("company1.pickle", "wb"))
# Reload the file
company1_reloaded = dill.load(open("company1.pickle", "rb"))
모든 캐시를 사용하여 작업을 수행할 수 있습니다.모든 세부사항을 고려합니다.
- 백엔드로 dill을 사용하여 python을 확장합니다.
pickle
handle " (처리하는 모듈)lambda
멋진 비단뱀의 특징도 모두 갖추어져 있습니다. - 다른 오브젝트를 다른 파일에 저장하고 적절하게 새로고침합니다.
- 캐시 크기 제한
- 캐시 클리어 가능
- 여러 실행 간에 객체를 공유할 수 있습니다.
- 결과에 영향을 미치는 입력 파일을 존중할 수 있습니다.
를 들어, ' 있다'라는 요.myfunc
이치노
from anycache import anycache
class Company(object):
def __init__(self, name, value):
self.name = name
self.value = value
@anycache(cachedir='/path/to/your/cache')
def myfunc(name, value)
return Company(name, value)
콜 " "myfunc
처음에 결과를 파일로 절임하다cachedir
고유 식별자(함수 이름과 인수에 따라 다름)를 파일명으로 사용합니다.을 사용하다 경우,cachedir
실행 실행에서 .
상세한 것에 대하여는, 메뉴얼을 참조해 주세요.
새로운 버전의 판다들은 또한 피클을 저장하는 기능을 가지고 있다.
그게 더 쉬울 것 같아요.
pd.to_pickle(object_to_save,'/temp/saved_pkl.pickle' )
언급URL : https://stackoverflow.com/questions/4529815/saving-an-object-data-persistence
'programing' 카테고리의 다른 글
JavaScript에서 변수가 정수인지 확인하는 방법 (0) | 2022.10.12 |
---|---|
목록을 자세히 복사하려면 어떻게 해야 합니까? (0) | 2022.10.12 |
YouTube API에서 YouTube 비디오 섬네일을 얻으려면 어떻게 해야 하나요? (0) | 2022.10.03 |
Java를 사용하여 16진수를 RGB로 변환하는 방법 (0) | 2022.10.03 |
롤링 기준으로 MySQL에서 오래된 행을 삭제하는 가장 좋은 방법은 무엇입니까? (0) | 2022.10.03 |