- json
1.1 dumps 把结构化数据转为字符串(比如dict–>str)
dict1 = {"name":"frankshi","age":26}
with open("test1.txt","w") as fp:
fp.write(dict1)
dict1 = {"name":"frankshi","age":26}
with open("test1.txt","w") as fp:
dict_str = json.dumps(dict1) #把结构化数据转为字符串
fp.write(dict_str)
1.2 loads把字符串转为结构化数据(比如str–>dict)
dict1 = {"name":"frankshi","age":26}
with open("test1.txt","r") as fp:
content = fp.read()
print(content)
#{"name": "frankshi", "age": 26}
print(content["name"])
dict1 = {"name":"frankshi","age":26}
with open("test1.txt","r") as fp:
content = fp.read()
print(content)
#{"name": "frankshi", "age": 26}
content = json.loads(content) #把字符串转为字典
print(content["name"]) #frankshi
1.3 dump 写入文件(可以直接写入字典等)
dict1 = {"name": "frankshi", "age": 26}
with open("test1.txt","w") as fp:
json.dump(dict1, fp)
1.4 load 读取文件内容
with open("test1.txt","r") as fp:
dict2 = json.load(fp)
print(dict2) #{'name': 'frankshi', 'age': 26}
print(dict2["name"]) #frankshi
- shelve
import shelve
fp = shelve.open("test2.txt")
#写入文件
fp["userinfo"] = {"name": "frankshi", "age": 26}
fp["user"] = ["frankshi1","shitou"]
#读取文件
print(fp["userinfo"]["name"])
#frankshi
print(fp["user"][1])
#shitou
#生成3个文件
test2.txt.bak
test2.txt.dat
test2.txt.dir