python中文件的操作2

1类型转换和eval函数

#程序中的数据存在文件中是否转化成字符串
#首先定义一个字典
users = {'username':'admin','password':'888','email':'123456qq.com'}
#将它转换成字符串
str_users = str(users)
#打开一个文件夹
with  open('./date/3.text','w')as file:
    file.write(str_users)

#再将它读取到程序中
with open('./date/3.text','r')as file2:
    s = file2.read()
    print(s,type(s))

#用eval吧它转换成字典
s = eval(s)
print(s,type(s))

2.json模块

import json
#准备一个字典
users = {'username':'admin','password':'234'}
#打开一个文件添加进去
with open('./date/4.text','w')as file:
    json.dump(users,file)

#输出
with open('./date/4.text','r')as file2:
    users = json.load(file2)
print(users,type(users))

3.marshal模块

'''
marshal模块练习
这是一个能将多个数据储存在文件中的模块
'''
import marshal

s = "字符串"
i = 3
b = True
t = (1,2)
l = [2,3]

x = [ i , b , t , l]
#打开一个文件夹
with open( './date/5.text', 'wb')as file:
    marshal.dump(len(x), file)
    for x1 in x:
        marshal.dump(x1, file)

#取出多个数据
with open('./date/5.text','rb')as file2:
    n = marshal.load(file2)
    for x2 in range(n):
        print(marshal.load(file2))

4shelve模块

#定义两个字典
users = {'admin': {'username': 'admin', 'password': '123', 'nickname': '大牧'}}
articles = {'标题': {'title': '标题', 'content': '文章内容', 'author': users.get('admin')}}

import shelve

file = shelve.open('./data/6.text')

#将多个数据按照key:value的形式存储到文件中
file['users'] = users
file['articles'] = articles

# 从文件中根据key读取数据
print(file['users'], type(file['users']))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值