Python——文件IO的四种读写操作

一 .  单独存储每条数据 

 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))   # 遍历,通过循环输出文件中的多条数据

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值