2020.04.15 파이썬 - Shelve
파이썬 Built-in에 이런 모듈이 있는것을 처음 알았다.
이렇게 파이썬 객체들 중 picklable 한 객체들은 모두 파일에 저장해둘 수 있고, 불러올 때도 모두 깔끔히 잘 불러와진다.
shelve.open의 writeback=True로 set하면 shelve.open에 이미 저장 된 값에 새로운 값을 덮어쓸 수 있다.
간단히 객체를 저장해두고 불러오면서 쓰기에는 부족함 없지 않을까 싶다.
import shelve class CustomClass: def __init__(self, value): self.value = value def __repr__(self): return f'<class: {self.__class__.__name__}>' with shelve.open('test.db') as f: f['my_int'] = 100 f['my_float'] = 100.555 f['my_str'] = 'hello world!' f['my_dict'] = dict(hello='world') f['my_custom_class'] = CustomClass('MyCustomClass') with shelve.open('test.db') as f: print(f['my_int']) print(f['my_float']) print(f['my_str']) print(f['my_dict']) print(f['my_custom_class']) print(f['my_custom_class'].value)
$ 100 $ 100.555 $ hello world! $ {'hello': 'world'} $ <class: CustomClass> $ MyCustomClass
이렇게 파이썬 객체들 중 picklable 한 객체들은 모두 파일에 저장해둘 수 있고, 불러올 때도 모두 깔끔히 잘 불러와진다.
shelve.open의 writeback=True로 set하면 shelve.open에 이미 저장 된 값에 새로운 값을 덮어쓸 수 있다.
with shelve.open('test.db', writeback=True) as f: f['my_list'] = [1, 2, 3, 4] f['my_list'].append(5) f['my_dict'] = dict(hello='world') f['my_dict']['hello'] = 'new_world' with shelve.open('test.db') as f: print(f['my_list']) print(f['my_dict']) # [1, 2, 3, 4, 5]# {'hello': 'new_world'}
간단히 객체를 저장해두고 불러오면서 쓰기에는 부족함 없지 않을까 싶다.
댓글
댓글 쓰기