008-random、shutil、shevle、标准输入输出错误流

random:随机数

Python中的random模块用于生成随机数。下面介绍一下random模块中最常用的几个函数。

(0, 1) 小数:random.random()
[1, 10] 整数:random.randint(1, 10)
[1, 10) 整数:random.randrange(1, 10)
(1, 10) 小数:random.uniform(1, 10)

 import random
 print(random.random())
 print(random.randint(1, 10))
 print(random.randrange(1, 10))
 print(random.uniform(1, 10))
 '''
 输出: 
0.047139223536078134
3
1
8.226478881835138
 ''' 

单例集合随机选择1个:random.choice(item)
单例集合随机选择n个:random.sample(item, n)
洗牌单列集合:random.shuffle(item)

import random
print(random.choice('abc'))
print(random.sample({1, 3, 5, 7, 9}, 3))
ls = [1, 2, 3, 4, 5]
random.shuffle(ls)
print(ls)
'''
输出:
b
[5, 7, 3]
[3, 4, 1, 2, 5]
'''

实例:产生指定位数的验证码

import random
def random_code(count):
    code = ''
    for i in range(count):
        num = random.randint(1, 3)
        if num == 1:
            tag = str(random.randint(0, 9))
        elif num == 2:
            tag = chr(random.randint(65, 90))
        else:
            tag = chr(random.randint(97, 122))
        code += tag
    return code
print(random_code(6))

shutil:可以操作权限的处理文件模块

基于路径的文件复制:
shutil.copyfile('source_file', 'target_file')

基于流的文件复制:
with open('source_file', 'rb') as r, open('target_file', 'wb') as w:
    shutil.copyfileobj(r, w)
    
递归删除目标目录
shutil.rmtree('target_folder')

文件移动
shutil.remove('old_file', 'new_file')

文件夹压缩
shutil.make_archive('file_name', 'format', 'archive_path')

文件夹解压
shutil.unpack_archive('unpack_file', 'unpack_name', 'format')

shevle:可以用字典存取数据到文件的序列化模块

shevle 模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是Python所支持的数据类型

将序列化文件操作dump与load进行封装
s_dic = shelve.open("target_file", writeback=True) 
注:writeback允许序列化的可变类型,可以直接修改值

序列化::存
s_dic['key1'] = 'value1'
s_dic['key2'] = 'value2'

反序列化:取
print(s_dic['key1'])

文件这样的释放
s_dic.close()


# 注意 :shelve 模块可以随时追加写入
import shelve

# f = shelve.open(r"shelve_1") # 这里加r 是一种习惯
# f["info"]={"name":"xue","age":"17"} # 写数据
with shelve.open("shelve_1") as f:
# f["ceshi"]="haha" # 也是写数据
print(f.get("ceshi"))
print(f.get("info"))
print(f.get("info")["name"])
print(f["ceshi"])

标准输入输出错误流

import sys
sys.stdout.write('msg')
sys.stderr.write('msg')
msg = sys.stdin.readline()

print默认是对sys.stdout.write('msg') + sys.stdout.write('\n')的封装
格式化结束符print:print('msg', end='')
posted @ 2020-03-18 22:01  xuefy  阅读(181)  评论(0)    收藏  举报