Python常用模块

time:时间

'''
时间戳(timestamp):time.time()
延迟线程的运行:time.sleep(secs)
(指定时间戳下的)当前时区时间:time.localtime([secs])
(指定时间戳下的)格林威治时间:time.gmtime([secs])
(指定时间元组下的)格式化时间:time.strftime(fmt[,tupletime])
'''
'''
%y 两位数的年份表示(00-99)
%Y 四位数的年份表示(000-9999)
%m 月份(01-12)
%d 月内中的一天(0-31)
%H 24小时制小时数(0-23)
%I 12小时制小时数(01-12)
%M 分钟数(00=59)
%S 秒(00-59)
%a 本地简化星期名称
%A 本地完整星期名称
%b 本地简化的月份名称
%B 本地完整的月份名称
%c 本地相应的日期表示和时间表示
%j 年内的一天(001-366)
%p 本地A.M.或P.M.的等价符
%U 一年中的星期数(00-53)星期天为星期的开始
%w 星期(0-6),星期天为星期的开始
%W 一年中的星期数(00-53)星期一为星期的开始
%x 本地相应的日期表示
%X 本地相应的时间表示
%Z 当前时区的名称
%% %号本身
'''

calendar:日历

'''
判断闰年:calendar.isleap(year)
查看某年某月日历:calendar.month(year, mouth)
查看某年某月起始星期与当月天数:calendar.monthrange(year, mouth)
查看某年某月某日是星期几:calendar.weekday(year, month, day)
'''

datatime:可以运算的时间

'''
当前时间:datetime.datetime.now()
昨天:datetime.datetime.now() + datetime.timedelta(days=-1)
修改时间:datatime_obj.replace([...])
格式化时间戳:datetime.date.fromtimestamp(timestamp)
'''

sys:系统

'''
命令行参数List,第一个元素是程序本身路径:sys.argv
退出程序,正常退出时exit(0):sys.exit(n) 
获取Python解释程序的版本信息:sys.version
最大int值:sys.maxsize | sys.maxint
环境变量:sys.path
操作系统平台名称:sys.platform
'''

os:操作系统

'''
生成单级目录:os.mkdir('dirname')
生成多层目录:os.makedirs('dirname1/.../dirnamen2')
重命名:os.rename("oldname","newname") 
工作目录:os.getcwd()
删除单层空目录:os.rmdir('dirname')
移除多层空目录:os.removedirs('dirname1/.../dirnamen') 
列举目录下所有资源:os.listdir('dirname')
路径分隔符:os.sep
行终止符:os.linesep
文件分隔符:os.pathsep
操作系统名:os.name
操作系统环境变量:os.environ
执行shell脚本:os.system() 
'''

os.path:系统路径操作

'''
执行文件的当前路径:__file__
返回path规范化的绝对路径:os.path.abspath(path)  
将path分割成目录和文件名二元组返回:os.path.split(path)  
上一级目录:os.path.dirname(path) 
最后一级名称:os.path.basename(path)
指定路径是否存在:os.path.exists(path)
是否是绝对路径:os.path.isabs(path)
是否是文件:os.path.isfile(path)
是否是路径:os.path.isdir(path) 
路径拼接:os.path.join(path1[, path2[, ...]])
最后存取时间:os.path.getatime(path)
最后修改时间:os.path.getmtime(path)
目标大小:os.path.getsize(path)
'''

案例

#不管项目在哪,都可以定位到项目根目录
import os.path
import sys
BASE_DIR = os.path.dirname(__file__)
#将项目根目录添加到环境变量
sys.path.append(BASE_DIR)
  • 判断目录是否存在不存在则创建,存在也不会报错
import os
if not os.path.exists('a'):    
        os.mkdir('a')

  • 递归目录删除
import os
import os.path

def remove_folder(path):
    # 路径是否合法
    if not os.path.exists(path):
        print('目标不存在')
        return True
    # 如果是文件,直接删除
    if os.path.isfile(path):
        os.remove(path)
        return True
    # 如果是文件夹,列出所有子文件及文件夹
    dir_list = os.listdir(path)
    for dir in dir_list:
        full_dir = os.path.join(path, dir,)
        # 是文件直接删除
        if os.path.isfile(full_dir):
            os.remove(full_dir)
        # 是文件夹就调直接,删除
        else:
            remove_folder(full_dir)
    # 上方循环走完,代表当前文件夹内部删空了,就能删除该文件夹了
    os.rmdir(path)
    return True
print(remove_folder('D:/资料/studypy/a/b'))
import os.path
import sys
BASE_DIR = os.path.dirname(__file__)
sys.path.append(BASE_DIR)
#完成上方操作,已经知道,项目得根目录已经在环境变量中
#在要将项目下的某个目录加到环境变量中
conf_path = os.path.join(BASE_DIR,"conf")
print(conf_path)
'''
normcase函数
在Linux和Mac平台上,该函数会原样返回path,在windows平台上会将路径中所有字符转换为小写,并将所有斜杠转换为饭斜杠。
>>> os.path.normcase('c:/windows\\system32\\')   
'c:\\windows\\system32\\'   
   
normpath函数
规范化路径,如..和/
>>> os.path.normpath('c://windows\\System32\\../Temp/')   
'c:\\windows\\Temp'   

>>> a='/Users/jieli/test1/\\\a1/\\\\aa.py/../..'
>>> print(os.path.normpath(a))
/Users/jieli/test1
'''

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

json:序列化

# json: {} 与 [] 嵌套的数据
# 注:json中的字符串必须全部用""来标识
'''
序列化:对象 => 字符串
序列化成字符串:json.dumps(json_obj)
序列化字符串到文件中:json.dump(json_obj, write_file)

# 注:字符形式操作
反序列化成对象:json.loads(json_str)
从文件读流中反序列化成对象:json.load(read_file)
'''

案例

import json
#序列化 对象 -> 字符串

dic = {
    'name':'deam',
    'age':18  #json支持的数据类型可以完成,不支持元组数据类型
}

json_str = json.dumps(dic)
print(json_str) #{"name": "deam", "age": 18}

#反序列号 字符串 -> 对象
json_str = '[1,2,3,4]'
lst = json.loads(json_str)
print(lst) #[1, 2, 3, 4]


#json序列化数据通常用于网络传输,但是也序列化到文件中
dic = {
    'name':'deam',
    'age':18,  #json支持的数据类型可以完成,不支持元组数据类型
    'sec':'男'
}
with open('jon.txt','w',encoding='utf-8') as f:
    #json默认采用的是ascii编码格式,要是想改变ensure_ascii=False
    json.dump(dic,f,ensure_ascii=False)

#从文件中反序列化
with open('jon.txt','r',encoding='utf-8') as f:
    resilt = json.load(f)
    print(resilt)

pickle:序列化

'''
序列化:对象 => 字符串
序列化成字符串:pickle.dumps(obj)
序列化字符串到文件中:pickle.dump(obj, write_bytes_file)

# 注:字节形式操作
反序列化成对象:pickle.loads(bytes_str)
从文件读流中反序列化成对象:pickle.load(read_bytes_file)
'''

案例

 import pickle

dic = {
    'name':'deam',
    'age':18,
    'sec':'男'
}
#pickle支持所有python中类型,序列化到文件中
with open('pikle','wb') as f:
    pickle.dump(dic,f)

with open('pikle','rb') as f:
    print(pickle.load(f))

#pickle序列化到字符串中
dic1 = {
    'name':'deam',
    'age':18,
    'sec':'女'
}
pik_byte = pickle.dumps(dic1)
print(type(pik_byte))

pik_dic = pickle.loads(pik_byte)
print(pik_dic)

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:可以用字典存取数据到文件的序列化模块

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

logging:日志模块

'''
1) root logging的基本使用:五个级别
2)root logging的基本配置:logging.basicConfig()
3)logging模块四个核心:Logger | Filter | Handler | Formater
4)logging模块的配置与使用
	-- 配置文件:LOGGING_DIC = {}
	-- 加载配置文件:logging.config.dictConfig(LOGGING_DIC) => logging.getLogger('log_name')
'''

re:正则模块(重点)

'''
1)模块的基本使用
2)正则的语法
3)分组:() | (?:) | (?P<name>)
4)正则的使用方法
'''

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())

hmac模块:加密

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

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

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('系统默认编码')

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

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")

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")
posted @ 2021-08-04 14:09  刘新元  阅读(44)  评论(0编辑  收藏  举报