python基础知识(七)常用模块----(四)

(七)常用模块----(四)

目录

(七)常用模块----(四)

7.1random模块

a.随机小数

b.随机整数

c.随机选择返回

d.打乱列表顺序

e.生成随机数

7.2序列化模块

a.json模块

b.pickle模块

c.shelve模块


7.1random模块

a.随机小数

import random
#随机小数
print(random.random() )     # 大于0且小于1之间的小数
print(random.uniform(1,3))  #大于1小于3的小数

b.随机整数

#随机整数
print(random.randint(1,5))  # 大于等于1且小于等于5之间的整数
print(random.randrange(1,10,2)) # 大于等于1且小于10之间的奇数

c.随机选择返回

#随机选择一个返回
print(random.choice([1,'23',[4,5]]))  # #1或者23或者[4,5]

#随机选择多个返回,返回的个数为函数的第二个参数
print(random.sample([1,'23',[4,5]],2)) # #列表元素任意2个组合

d.打乱列表顺序

# #打乱列表顺序
item=[1,3,5,7,9]
random.shuffle(item)
print(item) # 打乱次序

random.shuffle(item)
print(item)

e.生成随机数

import random

def v_code():

    code = ''
    for i in range(5):

        num=random.randint(0,9)
        alf=chr(random.randint(65,90))
        add=random.choice([num,alf])
        code="".join([code,str(add)])

    return code

print(v_code())

7.2序列化模块

序列化就是转向一个字符串数据类型

    从数据类型 --> 字符串的过程 序列化

    从字符串 --> 数据类型的过程 反序列化

a.json模块:

                    提供的功能:dumps、dump、loads、load

                    适用范围:数字 字符串 列表 字典 元组 

                     通用的序列化格式

                     只有很少的一部分数据类型能够通过json转化成字符串

  json dumps序列化方法 loads反序列化方法

dic = {1:"a",2:'b'}
print(type(dic),dic)
import json
str_d = json.dumps(dic)   # 序列化
print(type(str_d),str_d)

dic_d = json.loads(str_d) # 反序列化
print(type(dic_d),dic_d)
'''
<class 'dict'> {1: 'a', 2: 'b'}
<class 'str'> {"1": "a", "2": "b"}
<class 'dict'> {'1': 'a', '2': 'b'}
'''

 josn dump方法接收一个文件句柄,直接将字典转换成json字符串写入文件

          load方法接收一个文件句柄,直接将文件中的json字符串转换成数据结构返回

import json
# json dump load
dic = {1:"a",2:'b'}
f = open('aaa','w',encoding='utf-8')
json.dump(dic,f)
f.close()
f = open('aaa')
res = json.load(f)
f.close()
print(type(res),res)

#<class 'dict'> {'1': 'a', '2': 'b'}

ensure_ascii关键字参数

import json
dic = {1:"中国",2:'b'}
f = open('fff','w',encoding='utf-8')
json.dump(dic,f)
close(f)

import json
dic = {1:"中国",2:'b'}
f = open('fff','w',encoding='utf-8')
json.dump(dic,f,ensure_ascii=False)
f.close()

间接的把文件中每一行都输出:

l = [{'k':'111'},{'k2':'111'},{'k3':'111'}]
f = open('file','w')
import json
for dic in l:
    str_dic = json.dumps(dic)
    f.write(str_dic+'\n')
f.close()
import json
l = []
for line in f:
    dic = json.loads(line.strip())
    l.append(dic)
f.close()
print(l)
#[{'k': '111'}, {'k2': '111'}, {'k3': '111'}]

b.pickle模块: 

                         所有的python中的数据类型都可以转化成字符串形式

                         pickle序列化的内容只有python能理解,且部分反序列化依赖python代码

                         可以把文件中每一行直接输出

dic = {'k1':'v1','k2':'v2','k3':'v3'}
str_dic = pickle.dumps(dic)
print(str_dic)  #一串二进制内容

dic2 = pickle.loads(str_dic)
print(dic2)    #字典

import time
struct_time1  = time.localtime(1000000000)
struct_time2  = time.localtime(2000000000)
f = open('pickle_file','wb')
pickle.dump(struct_time1,f)
pickle.dump(struct_time2,f)
f.close()
f = open('pickle_file','rb')
struct_time1 = pickle.load(f)
struct_time2 = pickle.load(f)
print(struct_time1.tm_year)
print(struct_time2.tm_year)
f.close()
'''
2001
2033
'''

c.shelve模块: 

                   序列化句柄,使用句柄直接操作,非常方便

import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
f.close()

import shelve
f1 = shelve.open('shelve_file')
existing = f1['key']  #取出数据的时候也只需要直接用key获取即可,但是如果key不存在会报错
f1.close()
print(existing)

#{'int': 10, 'float': 9.5, 'string': 'Sample data'}

只读模式:改???

import shelve
f = shelve.open('shelve_file', flag='r')
existing = f['key']
print(existing)
f['key'] = 10
f.close()

f = shelve.open('shelve_file', flag='r')
existing2 = f['key']
f.close()
print(existing2)
'''
{'int': 10, 'float': 9.5, 'string': 'Sample data'}
10
'''
import shelve
f = shelve.open('shelve_file')
f['key'] = {'int':10, 'float':9.5, 'string':'Sample data'}  #直接对文件句柄操作,就可以存入数据
f.close()

f1 = shelve.open('shelve_file')
print(f1['key'])
f1['key']['new_value'] = 'this was not here before'
f1.close()

#{'int': 10, 'float': 9.5, 'string': 'Sample data'}


f1 = shelve.open('shelve_file')
print(f1['key'])
f1.close()
#{'int': 10, 'float': 9.5, 'string': 'Sample data'} 并未写入


f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
f2['key']['new_value'] = 'this was not here before'
f2.close()

f2 = shelve.open('shelve_file', writeback=True)
print(f2['key'])
f1.close()
#{'int': 10, 'float': 9.5, 'string': 'Sample data', 'new_value': 'this was not here before'} 写进文件

 

  • 1
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值