python shelve模块

Posted F

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了python shelve模块相关的知识,希望对你有一定的参考价值。

 

#coding=utf-8
import shelve

f = shelve.open("shelve_test")
f[info] = "alex"
f["age"] = [1,34,5,6,33,44]
f["name"] = {"name":"alex","add":"sz"}
f.close()

f = shelve.open("shelve_test")
# 这里这个f我们就可以理解为是一个字典对象,所以shelve存储数据就按照字典的方式存储数据


print(f.get("info"))
print(f.get("age"))
print(f.get("name"))
print(f[info])
print(f.values())
print(f.items())
print(f.keys())

输出

alex
[1, 34, 5, 6, 33, 44]
{name: alex, add: sz}
alex
ValuesView(<shelve.DbfilenameShelf object at 0x000001A88D374208>)
ItemsView(<shelve.DbfilenameShelf object at 0x000001A88D374208>)
KeysView(<shelve.DbfilenameShelf object at 0x000001A88D374208>)

 

#coding=utf-8
import shelve
with shelve.open("test_shelve.db") as f:
    f["k1"] = {
        "name":"xiaoming1",
        "age":12,
        "address":"beijing1"
    }
    f["k2"] = {
        "name":"xiaoming2",
        "age":12,
        "address":"beijing2"
    }
    f["k3"] = {
        "name":"xiaoming3",
        "age":12,
        "address":"beijing3"
    }
    f["k4"] = ["小明1","小明2","小明3"]
with shelve.open("test_shelve.db") as f:
    print(f["k1"]["name"])
    print(f["k4"][0])

输出

xiaoming1
小明1

 

#coding=utf-8
import shelve
test_list=[1,2,3,4,5]
test_dict={"aaa":23,"bbb":33}
s="xiaoming"
with shelve.open("shelve.ini","wc") as f:
    f["k1"] = test_list
    f["k2"] = test_dict
    f["k3"] = s
 
with shelve.open("shelve.ini","rc") as k:
    print(k["k3"])
    print(k["k2"])
    print(k["k1"])

输出

xiaoming
{aaa: 23, bbb: 33}
[1, 2, 3, 4, 5]

 

#coding=utf-8
import shelve


list = [1, 2, 3]
she = shelve.open(test.dat)
she[d] = list
she[d].append(f)
print(she[d])


list = [1, 2, 3]
she = shelve.open(test.dat)
she[d] = list
temp = she[d]
temp.append(f)
she[d] = temp
print(she[d])

输出

[1, 2, 3]
[1, 2, 3, f]

 

以上是关于python shelve模块的主要内容,如果未能解决你的问题,请参考以下文章

Python模块-shelve模块

python模块(shelve,xml,configparser,hashlib,logging)

python模块(shelve,xml,configparser,hashlib,logging)

python shelve模块

python shelve模块

python shelve模块