【发布时间】:2017-08-20 22:41:09
【问题描述】:
我正在尝试在 python 中使用 shelve 模块,并尝试将其与“with”语句结合使用,但是在尝试这样做时出现以下错误:
with shelve.open('shelve', 'c') as shlv_file:
shlv_file['title'] = 'The main title of my app'
shlv_file['datatype'] = 'data type int32'
shlv_file['content'] = 'Lorem ipsum'
shlv_file['refs'] = '<htppsa: asda.com>'
print(shlv_file)
出现以下错误:
with shelve.open('shelve', 'c') as shlv_file:
AttributeError: DbfilenameShelf instance has no attribute '__exit__'
虽然这样做:
shlv_file = shelve.open('data/shelve', 'c')
shlv_file['title'] = 'The main title of my app'
shlv_file['datatype'] = 'data type int32'
shlv_file['content'] = 'Lorem ipsum'
shlv_file['refs'] = '<htppsa: asda.com>'
shlv_file.close()
shlv_file = shelve.open('data/shelve', 'c')
shlv_file['new_filed'] = 'bla bla bla'
print(shlv_file)
没有引发错误,并且输出是预期的。第一种语法有什么问题?我在看一个python课程,讲师使用第一个版本没有任何问题。
【问题讨论】:
-
你的 Python 版本是多少?根据the documentation,在 3.4 中添加了上下文管理器支持(
with块)。
标签: python persistence shelve