Python常用模块2

简介: Python常用模块

10. random:随机数


(0, 1) 小数:random.random()
[1, 10] 整数:random.randint(1, 10)
[1, 10) 整数:random.randrange(1, 10)
(1, 10) 小数:random.uniform(1, 10)
单例集合随机选择1个:random.choice(item)
单例集合随机选择n个:random.sample(item, n)
洗牌单列集合:random.shuffle(item)


# 产生指定位数的验证码
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)) 


11. 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')



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


# 将序列化文件操作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()


12.1 三流:标准输入输出错误流


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='')


13. hashlib模块:加密


import hashlib
# 基本使用
cipher = hashlib.md5('需要加密的数据的二进制形式'.encode('utf-8'))
print(cipher.hexdigest())  # 加密结果码
# 加盐
cipher = hashlib.md5()
cipher.update('前盐'.encode('utf-8'))
cipher.update('需要加密的数据'.encode('utf-8'))
cipher.update('后盐'.encode('utf-8'))
print(cipher.hexdigest())  # 加密结果码
# 其他算法
cipher = hashlib.sha3_256(b'')
print(cipher.hexdigest())
cipher = hashlib.sha3_512(b'')
print(cipher.hexdigest())


14. hmac模块:加密


# 必须加盐
cipher = hmac.new('盐'.encode('utf-8'))
cipher.update('数据'.encode('utf-8'))
print(cipher.hexdigest())


15. configparser模块:操作配置文件


# my.ini
[section1]
option1_1 = value1_1
option1_2 = value1_2
[section2]
option2_1 = value2_1
option2_2 = value2_2
import configparser
parser = configparser.ConfigParser()
# 读
parser.read('my.ini', encoding='utf-8')
# 所有section
print(parser.sections())  
# 某section下所有option
print(parser.options('section_name'))  
# 某section下某option对应的值
print(parser.get('section_name', 'option_name')) 
# 写
parser.set('section_name', 'option_name', 'value')
parser.write(open('my.ini', 'w'))


16. subprocess模块:操作shell命令


import subprocess
order = subprocess.Popen('终端命令', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
suc_res = order.stdout.read().decode('系统默认编码')
err_res = order.stderr.read().decode('系统默认编码')
order = subprocess.run('终端命令', shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
suc_res = order.stdout.decode('系统默认编码')
err_res = order.stderr.decode('系统默认编码')



17. xlrd模块:excel读


年终报表 
教学部 市场部 咨询部 总计
Jan-19 10 15 5 30
Feb-19 10 15 5 30
Mar-19 10 15 5 30
Apr-19 10 15 5 30
May-19 10 15 5 30
Jun-19 10 15 5 30
Jul-19 10 15 5 30
Aug-19 10 15 5 30
Sep-19 10 15 5 30
Oct-19 10 15 5 30
Nov-19 10 15 5 30
Dec-19 10 15 5 30
import xlrd
# 读取文件
work_book = xlrd.open_workbook("机密数据.xlsx")
# 获取所有所有表格名称
print(work_book.sheet_names())
# 选取一个表
sheet = work_book.sheet_by_index(1)
# 表格名称
print(sheet.name)
# 行数
print(sheet.nrows)
# 列数
print(sheet.ncols)
# 某行全部
print(sheet.row(6))
# 某列全部
print(sheet.col(6))
# 某行列区间
print(sheet.row_slice(6, start_colx=0, end_colx=4))
# 某列行区间
print(sheet.col_slice(3, start_colx=3, end_colx=6))
# 某行类型 | 值
print(sheet.row_types(6), sheet.row_values(6))
# 单元格
print(sheet.cell(6,0).value) # 取值
print(sheet.cell(6,0).ctype) # 取类型
print(sheet.cell_value(6,0)) # 直接取值
print(sheet.row(6)[0])
# 时间格式转换
print(xlrd.xldate_as_datetime(sheet.cell(6, 0).value, 0))


18. xlwt模块:excel写


import xlwt
# 创建工作簿
work = xlwt.Workbook()
# 创建一个表
sheet = work.add_sheet("员工信息数据")
# 创建一个字体对象
font = xlwt.Font()
font.name = "Times New Roman"  # 字体名称
font.bold = True  # 加粗
font.italic = True  # 斜体
font.underline = True  # 下划线
# 创建一个样式对象
style = xlwt.XFStyle()
style.font = font
keys = ['Owen', 'Zero', 'Egon', 'Liuxx', 'Yhh']
# 写入标题
for k in keys:
    sheet.write(0, keys.index(k), k, style)
# 写入数据
sheet.write(1, 0, 'cool', style)
# 保存至文件
work.save("test.xls")


19. xml模块


<?xml version="1.0"?>
<data>
    <country name="Liechtenstein">
        <rank updated="yes">2</rank>
        <year>2008</year>
        <gdppc>141100</gdppc>
        <neighbor name="Austria" direction="E"/>
        <neighbor name="Switzerland" direction="W"/>
    </country>
    <country name="Singapore">
        <rank updated="yes">5</rank>
        <year>2011</year>
        <gdppc>59900</gdppc>
        <neighbor name="Malaysia" direction="N"/>
    </country>
    <country name="Panama">
        <rank updated="yes">69</rank>
        <year>2011</year>
        <gdppc>13600</gdppc>
        <neighbor name="Costa Rica" direction="W"/>
        <neighbor name="Colombia" direction="E"/>
    </country>
</data>
import xml.etree.ElementTree as ET
# 读文件
tree = ET.parse("xmltest.xml")
# 根节点
root_ele = tree.getroot()
# 遍历下一级
for ele in root_ele:
    print(ele)
# 全文搜索指定名的子标签
ele.iter("标签名")
# 非全文查找满足条件的第一个子标签
ele.find("标签名")
# 非全文查找满足条件的所有子标签
ele.findall("标签名")
# 标签名
ele.tag
# 标签内容
ele.text
# 标签属性
ele.attrib
# 修改
ele.tag = "新标签名"
ele.text = "新文本"
ele.set("属性名", "新属性值")
# 删除
sup_ele.remove(sub_ele)
# 添加
my_ele=ET.Element('myEle')
my_ele.text = 'new_ele'
my_ele.attrib = {'name': 'my_ele'}
root.append(my_ele)
# 重新写入硬盘
tree.write("xmltest.xml")
目录
相关文章
|
3天前
|
JSON 数据格式 Python
Python标准库中包含了json模块,可以帮助你轻松处理JSON数据
【4月更文挑战第30天】Python的json模块简化了JSON数据与Python对象之间的转换。使用`json.dumps()`可将字典转为JSON字符串,如`{&quot;name&quot;: &quot;John&quot;, &quot;age&quot;: 30, &quot;city&quot;: &quot;New York&quot;}`,而`json.loads()`则能将JSON字符串转回字典。通过`json.load()`从文件读取JSON数据,`json.dump()`则用于将数据写入文件。
9 1
|
4天前
|
Python 容器
python内置函数、数学模块、随机模块(二)
python内置函数、数学模块、随机模块(二)
|
4天前
|
索引 Python
python内置函数、数学模块、随机模块(一)
python内置函数、数学模块、随机模块(一)
|
7天前
|
人工智能 安全 Java
Python 多线程编程实战:threading 模块的最佳实践
Python 多线程编程实战:threading 模块的最佳实践
123 5
|
7天前
|
人工智能 数据库 开发者
Python中的atexit模块:优雅地处理程序退出
Python中的atexit模块:优雅地处理程序退出
8 3
|
10天前
|
存储 开发者 Python
Python中的argparse模块:命令行参数解析的利器
Python中的argparse模块:命令行参数解析的利器
16 2
|
10天前
|
开发者 Python
Python的os模块详解
Python的os模块详解
17 0
|
13天前
|
数据挖掘 API 数据安全/隐私保护
python请求模块requests如何添加代理ip
python请求模块requests如何添加代理ip
|
14天前
|
测试技术 Python
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
Python 有趣的模块之pynupt——通过pynput控制鼠标和键盘
|
15天前
|
Serverless 开发者 Python
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
《Python 简易速速上手小册》第3章:Python 的函数和模块(2024 最新版)
42 1