python使用shelve保存变量

Python (205) 2023-04-18 14:05:50

1、用shelve模块,可以将Python中的变量保存到二进制的shelf文件中。

这样,程序就可以从硬盘中恢复变量的数据。

纯文本
复制到剪贴板
在新窗口中打开代码
EnlighterJS 3 Syntax Highlighter
importshelve
shelfFile=shelve.open('mydata')
cats=['Zonphie','Pooka','Simon']
shelfFile['cats']=cats
shelfFile.close()
importshelve shelfFile=shelve.open('mydata') cats=['Zonphie','Pooka','Simon'] shelfFile['cats']=cats shelfFile.close()
importshelve
shelfFile=shelve.open('mydata')
cats=['Zonphie','Pooka','Simon']
shelfFile['cats']=cats
shelfFile.close()

2、shelf值不必用读模式或写模式打开,因为打开后,既能读又能写。

纯文本
复制到剪贴板
在新窗口中打开代码
EnlighterJS 3 Syntax Highlighter
shelfFile=shelve.open('mydata')
type(shelfFile)
shelve.DbfilenameShelf
shelfFile['cats']
shelfFile.close()
shelfFile=shelve.open('mydata') type(shelfFile) shelve.DbfilenameShelf shelfFile['cats'] shelfFile.close()
shelfFile=shelve.open('mydata')
type(shelfFile)

shelve.DbfilenameShelf

shelfFile['cats']

shelfFile.close()

以上就是python使用shelve保存变量的方法,希望对大家有所帮助。

本文教程操作环境:windows7系统、Python 3.9.1,DELL G3电脑。

THE END

发表回复