python文件IO操作(二)

python存取数据到文件中:
1、每个独立的数据都要存储为一个文件
(1)、存 str() 取 eval()
(2)、存 json.dump() 取 json.load()

2、存储多个数据到一个文件中
(1)、存 marshal.dump() 取 marshal.load()
(2)、打开 file = shelve.open()

1.1.1 将程序中的字典数据,转换成字符串存储到文件中
users = {‘admin’:{‘username’:‘admin’,‘password’:‘123’,‘nickname’:‘朱正廷’}}

#字典可直接转换为字符串
users_str = str(users)

#存储到文件中
with open(’./data/2.1.text’,‘w’) as file:
file.write(users_str)

1.1.2 将文件中的字符串数据,读取到程序中(eval 将字符串转化为字典)
with open(’./data/2.1.text’,‘r’) as file:
users = file.read()
print(users,type(users))

# 将字符串数据,转换为字典:该字符串的格式和python中的字典的表达式一致
users = eval(users)
print(users,type(users))
print(users.get('admin'))

在这里插入图片描述

1.2.1 将程序中的数据,直接存储到文件中
import json
#json模块,可以直接对python中的数据进行序列化操作
users = {‘admin’:{‘username’:‘admin’,‘password’:‘123’,‘nickname’:‘朱正廷’}}

with open(’./data/3.1.json’,‘w’) as file:
json.dump(users,file)

1.2.2 将文件中的数据,读取到程序中

with open(’./data/3.1.json’,‘r’) as file:
users = json.load(file)
print(users,type(users))

在这里插入图片描述

2.1.1 存储多个数据到文件中
import marshal
#按照列表方式存储多个数据的模块:marshal
s =‘朱正廷’
f = 3.18
b = True
l =[3,1,8]
d ={‘username’:‘朱正廷’,‘age’:22}

x =[s,f,b,l,d]

with open(’./data/4.1.txt’,‘wb’) as file:
#第一次存储一个数量:有多少数据存储到文件中
marshal.dump(len(x),file)

# 第二次存储每个数据
for i in x:
    marshal.dump(i,file)

2.1.2 将多个数据从文件中依次取出
with open(’./data/4.1.txt’,‘rb’) as file:
#第一次取出存储数据的数量
n = marshal.load(file)

# 第二次将所有数据依次取出
for x in range(n):
    print(marshal.load(file))

在这里插入图片描述

2.2.1 将多个数据按照key:value的形式存储到文件中
users = {‘admin’:{‘username’:‘admin’,‘password’:‘123’,‘nickname’:‘朱正廷’}}
articles = {‘标题’:{‘title’:‘标题’,‘content’: ‘文章内容’, ‘author’:users.get(‘admin’)}}

file = shelve.open(’./data/5.1’)

file[‘users’] = users
file[‘articles’] = articles

2.2.2 从文件中根据key读取数据

print(file[‘users’],type(file[‘users’]))
print(file[‘articles’], type(file[‘articles’]))

在这里插入图片描述

猜你喜欢

转载自blog.csdn.net/qq_40908334/article/details/86663871