programing tip

파이썬에서 여러 변수를 어떻게 저장하고 복원합니까?

itbloger 2020. 8. 30. 07:48
반응형

파이썬에서 여러 변수를 어떻게 저장하고 복원합니까?


약 12 개의 개체를 파일에 저장 한 다음 나중에 복원해야합니다. pickle 및 shelve와 함께 for 루프를 사용하려고 시도했지만 제대로 작동하지 않았습니다.

편집하다.
내가 저장하려는 모든 객체는 같은 클래스에 있었으며 (이전에 언급 했어야했던) 다음과 같이 전체 클래스를 저장할 수 있다는 것을 몰랐습니다.

def saveLoad(opt):
    global calc
    if opt == "save":
        f = file(filename, 'wb')
        pickle.dump(calc, f, 2)
        f.close
        print 'data saved'
    elif opt == "load":
        f = file(filename, 'rb')
        calc = pickle.load(f)
    else:
        print 'Invalid saveLoad option'

여러 객체를 저장해야하는 경우에는 간단히 단일 목록 또는 튜플에 넣을 수 있습니다. 예를 들면 다음과 같습니다.

import pickle

# obj0, obj1, obj2 are created here...

# Saving the objects:
with open('objs.pkl', 'w') as f:  # Python 3: open(..., 'wb')
    pickle.dump([obj0, obj1, obj2], f)

# Getting back the objects:
with open('objs.pkl') as f:  # Python 3: open(..., 'rb')
    obj0, obj1, obj2 = pickle.load(f)

당신은 많은 양의 데이터가있는 경우, 당신은 전달하여 파일 크기를 줄일 수 있습니다 protocol=-1dump(); pickle그러면 기본 기록 (및 더 이전 버전과 호환되는) 프로토콜 대신 사용 가능한 최상의 프로토콜을 사용합니다. 이 경우 파일은 바이너리 모드 ( wbrb각각) 에서 열어야합니다 .

바이너리 모드는 기본 프로토콜이 바이너리 (즉, 텍스트가 아닌) 데이터 (쓰기 모드 'wb'및 읽기 모드 'rb')를 생성하므로 Python 3에서도 사용해야합니다 .


라는 내장 라이브러리가 pickle있습니다. 를 사용 pickle하면 객체를 파일로 덤프하고 나중에로드 할 수 있습니다.

import pickle

f = open('store.pckl', 'wb')
pickle.dump(obj, f)
f.close()

f = open('store.pckl', 'rb')
obj = pickle.load(f)
f.close()

shelvepickle 모듈을 살펴보아야 합니다. 많은 데이터를 저장해야하는 경우 데이터베이스를 사용하는 것이 좋습니다.


klepto메모리, 디스크 또는 데이터베이스에 대한 영구 캐싱을 제공하는을 사용할 수 있습니다 .

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[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.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db['1'] = 1
>>> db['max'] = max
>>> squared = lambda x: x**2
>>> db['squared'] = squared
>>> def add(x,y):
...   return x+y
... 
>>> db['add'] = add
>>> class Foo(object):
...   y = 1
...   def bar(self, x):
...     return self.y + x
... 
>>> db['Foo'] = Foo
>>> f = Foo()
>>> db['f'] = f  
>>> db.dump()
>>> 

그런 다음 통역사가 다시 시작한 후 ...

dude@hilbert>$ python
Python 2.7.6 (default, Nov 12 2013, 13:26:39) 
[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.
>>> from klepto.archives import file_archive
>>> db = file_archive('foo.txt')
>>> db
file_archive('foo.txt', {}, cached=True)
>>> db.load()
>>> db
file_archive('foo.txt', {'1': 1, 'add': <function add at 0x10610a0c8>, 'f': <__main__.Foo object at 0x10510ced0>, 'max': <built-in function max>, 'Foo': <class '__main__.Foo'>, 'squared': <function <lambda> at 0x10610a1b8>}, cached=True)
>>> db['add'](2,3)
5
>>> db['squared'](3)
9
>>> db['f'].bar(4)
5
>>> 

여기에서 코드 받기 : https://github.com/uqfoundation


피클 파일에 여러 변수를 저장하는 또 다른 방법은 다음과 같습니다.

import pickle

a = 3; b = [11,223,435];
pickle.dump([a,b], open("trial.p", "wb"))

c,d = pickle.load(open("trial.p","rb"))

print(c,d) ## To verify

다음 접근 방식은 간단 해 보이며 크기가 다른 변수와 함께 사용할 수 있습니다.

import hickle as hkl
# write variables to filename [a,b,c can be of any size]
hkl.dump([a,b,c], filename)

# load variables from filename
a,b,c = hkl.load(filename)

참고URL : https://stackoverflow.com/questions/6568007/how-do-i-save-and-restore-multiple-variables-in-python

반응형