• home
  • about
  • 全ての投稿
  • ソフトウェア・ハードウェアの設定のまとめ
  • 分析関連のまとめ
  • ヘルスケア関連のまとめ
  • 生涯学習関連のまとめ

python shelve

date: 2022-12-28 excerpt: pythonのshelveの使い方

tag: pythonpython3shelvepermanentdbm


pythonのshelveの使い方

概要

  • dictの操作性のデータ構造を恒久化するpythonのデフォルトのライブラリ
  • dbmとpickleで作られているらしい
  • open, closeのオペレーションが必要
    • つまり、マルチプロセスなどには対応しない

恒久化のタイミング

  • =で値を代入したとき

具体例

  • twitterのshort url(t.co)を展開するプログラムの例
import requests
import pandas as pd
import shelve

def reverse_tco(url):
    with shelve.open("dic") as dic:
        if dic.get(url) is None:
            r = requests.head(url)
            location = r.headers.get("Location")
            dic[url] = location # この時点で保存
        location = dic[url]
    return location

参考

  • shelve — Python object persistence/docs.python.org


pythonpython3shelvepermanentdbm Share Tweet