Python中数据类型转换的输入与输出

1、使用eval()函数的数据类型的转换

#1. 将程序中的字典数据,转换成字符串存储到文件中
users = {'admin': {'username': 'admin', 'password': '123'}}
# 类型能否直接转换字符串?
users_str = str(users)
# 存储到文件中
with open('./data/2.1.text', 'w') as file:
    file.write(users_str)


# 2. 将文件中的字符串数据,读取到程序中
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'))

2、使用json模块的转换

import json
#准备数据的 操作
users={"admin":{"username":"admin","password":"123"}}
#1.将程序中的数据,直接储存到文件中
#json模块操作
with open("./data/3.1.json","w")as file:
    json.dump(users,file)
#2.将文件中的数据,读取到程序中
with open("./data/3.1.json",'r')as file:
    users=json.load(file)
    print(users,type(users))

3、使用marshal模块的多个数据的转换

#数据准备
a="asd"
b=23
c=['ad','sad']
d={'asd':'sadas'}
x=[a,b,c,d]

#储存多个数据的模块  marshal
import marshal
#1.储存多个数据到文件中
with open('./data/4.1.dat','wb')as file:
    #第一次储存一个数量:有多个数据储存到了文件中
    marshal.dump(len(x),file)
    #储存每个数据
    for x1 in x:
        marshal.dump(x1,file)

#2.将多个数据从文件中依次取出
with open('./data/4.1.dat','rb')as file:
    n=marshal.load(file)

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

4、使用shelve模块的转换

#数据的准备
users={'admin':{"admin":"admin"}}
articles={"title":{"title":"标题"}}

import shelve
file=shelve.open("./data/5.1")
#1.将多个数据按照key:value的形式储存到文件中
file['users']=users
file['articles']=articles
#2.从文件中根据key读取数据
print(file['users'],type(file['users']))

猜你喜欢

转载自blog.csdn.net/A994958/article/details/86663595
今日推荐