Python3 Shelve:如何永久附加值?

时间:2017-07-25 15:09:49

标签: python-3.x append shelve

我希望用户在shelve模块中添加新值。每次关闭文件时,附加的值都会消失。

import shelve


shelvePracticeFile = shelve.open('/shelvePractice', writeback=True)

shelvePracticeFile['funnyNames'] = ['lala', 'dada', 'mama', 'baba']
shelvePracticeFile['funnyNumbers'] = [3,9,18]
shelvePracticeFile['funnySkills'] = ['Python', 'Football', 'Gaming']

# Will try to append.

print('Lets try to append. Type in something')
myInput = input()

shelvePracticeFile['funnySkills'].append(myInput)

# Lets read and print the shelve file we've created!

print(shelvePracticeFile['funnyNames'])
print(shelvePracticeFile['funnyNumbers'])
print(shelvePracticeFile['funnySkills'])


shelvePracticeFile.close()

2 个答案:

答案 0 :(得分:0)

此代码实际上可以运行并保存到Shelve中。对于像我这样的初学者;如果你一遍又一遍地运行上面的代码,shelvePracticeFile['funnySkills'] = ['Python', 'Football', 'Gaming']部分将重写字典并删除你附加的值。

我希望这可以帮助其他犯同样错误的人:)

答案 1 :(得分:0)

我有同样的问题,但即使在第一次也没有说话。

import shelve
file_name="sh"

data=shelve.open(file_name)
for i in range(ord('a'),ord('z')):
    data[chr(i)]=[]

word='angry!'
data[word[0]].append(word)
print(data[word[0]])
data.close()
data=shelve.open(file_name)
for i in data: print(i, data[i])

有趣的是,如果我使用数据[word [0]] + = [word]而没有数据[word [0]]。append(word),一切正常。指针可能有问题吗?