将 Python 搁置从 dbm.gnu 转换为 dbm.dumb

Convert Python shelve from dbm.gnu to dbm.dumb

我正在尝试将存储在非哑搁架中的数据转换为哑搁置,以便能够在未安装非哑库的位置访问我的数据。

我转换数据库数据的测试代码如下所示:

import numpy as np
import shelve
import dbm

# create test shelve
sample = list(range(0, 10))
filename = 'test'
new_filename = 'test-dumb'

with shelve.open(filename) as data:
    data['sample'] = sample
print('current db type: ', dbm.whichdb(filename))


# test test shelve
with shelve.open(filename) as data:
    print('in current db: ', list(data.keys()))


# read test shelve
with shelve.open(filename) as data:
    # store in dumb format
    with dbm.dumb.open(new_filename) as dumb_data:
        dumb_data = data
        print('in new db: ', list(dumb_data.keys()))
print('\nnew db type: ', dbm.whichdb(new_filename))


# check dumb shelve
with dbm.dumb.open(new_filename) as dumb_data:
    print(list(dumb_data.keys()))
    if dumb_data['sample'] == sample:
        print('success: ', sample)
    else:
        print('not yet: ', sample)

输出如下:

current db type:  dbm.gnu
in current db:  ['sample']
in new db:  ['sample']
new db type:  dbm.dumb
[]
Traceback (most recent call last):
  File "/home/asdf/anaconda3/envs/phievo/lib/python3.7/dbm/dumb.py", line 153, in __getitem__
    pos, siz = self._index[key]     # may raise KeyError
KeyError: b'sample'

我做错了什么?

您需要遍历原始数据库的键,赋值:

dumb_data = data

只会用指向 data 的“指针”覆盖 dumb_data 变量。

程序应如下所示:

import numpy as np
import shelve
import dbm

...

# copy data into dumb
with shelve.open(filename) as data:
    # store in dumb format
    with dbm.dumb.open(new_filename) as dumb_data:
        for key, value in data.items():
            dumb_data[key] = value
        print('in new db: ', list(dumb_data.keys()))

我刚刚将作业替换为:

for key, value in data.items(): 
    dump_data[key] = value`