一 . 单独存储每条数据
1. str()转字符串存储;eval()转数据类型读取
d = {'user':{'name':'qq','pass':'123','age':'18'}}
with open('./test.txt', 'w') as file:
file.write(str(d)) # 转字符串存储
with open('./test.txt', 'r') as file:
f = file.read()
f = eval(f) # 转数据类型读取
print(f,type(f))
2. json.dump()存储到文件;json.load()读取数据
import json
d = {'user':{'name':'qq','pass':'123','age':'18'}}
with open('./json.txt', 'w') as file:
json.dump(d,file) # 将对象存储到文件
with open('./json.txt', 'r') as file:
f = json.load(file) # 按数据原类型读取数据
print(f, type(f))
二 . 存储多个数据
3. shelve 模块
import shelve
file = shelve.open('./test')
# 将多条数据写入文件
file['admin'] = {'username':'admin','password':'123','nickname':'猪猪'}
file['user'] = {'username':'user','password':'111','nickname':'zz'}
# 从文件中读取多条数据
user = file['admin']
users = file['user']
# 打印结果
print(user,type(user))
print(users,type(users))
4. marshal 模块
import marshal
s = '汉族'
i = 99
f = 3.14159
b = True
c = 11 + 3j
l = [1,2,3]
d = {'name':'qq','pass':'123'}
x = [s,i,f,b,c,l,d]
with open('./marshal.dat', 'wb') as file:
marshal.dump(len(x),file) # 存储列表x的长度
for x1 in x:
marshal.dump(x1,file) # 存储列表中多条数据内容
with open('./marshal.dat', 'rb') as file:
n = marshal.load(file) # 读取文件中数据长度
for x in range(n):
print(marshal.load(file)) # 遍历,通过循环输出文件中的多条数据