1

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

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

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'

我在这里做错了什么?

4

1 回答 1

2

您需要遍历原始数据库的键,分配:

dumb_data = data

只会dumb_data用指向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`
于 2020-09-22T12:02:32.937 回答