zoukankan      html  css  js  c++  java
  • python模块

    time模块

    """
    三种时间表显现形式:
    时间戳:给电脑看(1920,1,1)按秒计算
    格式化时间(format String):给人看,返回2019-11-16
    格式化时间对象(struct_time):返回一个元组,九个值
    """
    import time

    获得时间戳

    print(time.time())

    获取格式化时间

    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    print(time.strftime('%Y-%m-%d %X'))#%X ==%H:%M:%S

    获取时间对象

    print(time.localtime())
    print(type(time.localtime()))#元组类对象
    res = time.localtime()
    print(res.tm_hour)#通过.调取元组里边的值

    res = time.localtime()
    time.sleep(5)
    print(time.strftime('%Y-%m-%d %H:%M:%S'))
    print(time.strftime('%Y-%m-%d %H:%M:%S',time.localtime()))

    将时间对象转化为格式化时间

    print(time.strftime('%Y-%m-%d %H:%M:%S',res))

    将字符串按格式的时间转化为实践对象

    res = time.strptime('2019-01-01','%Y-%m-%d')
    print(res.tm_mday)#字符串里不包含的调取元组为0
    print(time.localtime())

    datetime 模块
    import datetime
    获取当前年月日
    print(datetime.date.today())
    print(datetime.datetime.now())

    获取当前年月日时分秒

    print(datetime.datetime.today())
    res = datetime.datetime.today()
    print(type(res))#<>
    print(res.year)#获取现在的年份

    从索引0开始计算周一

    UTC

    print(res.weekday())

    ISO

    print(res.isoweekday())
    UTC时区,别经时间
    print(datetime.datetime.now()) #与 datetime.datetime.today()

    格林威治时间

    print(datetime.datetime.utcnow())
    '''
    日期时间 = 日期时间"+" or "-" 时间对象
    时间对象 = 日期时间"+" or '-'日期时间

    '''

    获取日期时间

    ct = datetime.datetime.now()
    print(ct)

    获取实践对象 获取七天时间

    time_obj = datetime.timedelta(minutes=24)#此处可以传days,seconds,microseconds,milliseconds,minutes,hours,weeks

    获取当前时间24小时以前的时间

    later_time = ct+time_obj#加时以后,减时以前
    print(later_time)
    new_time_obj =later_time - ct
    print(new_time_obj)#输出时间对象

    random函数
    import random
    random.randint(1,9)#随机生成1-9

    random.random()#生成0-1之间任意小数

    l = ['j','q','k','a']
    random.shuffle(l)#原列表打乱
    print(l)
    res = random.choice(l)
    print(res)
    """

    需求:
    大小写字母、数字组合而成
    组合5位数的随机验证码

    前置技术:
    - chr(97) # 可以将ASCII表中值转换成对应的字符
    # print(chr(101))
    - random.choice

    """
    def yz(n):
    s = ''
    for i in range(n):
    res = random.randint(65,90)
    capital = chr(res)
    res2 = random.randint(97,122)
    lower = chr(res2)
    res3 = str(random.randint(0,9))
    number = res3
    dic =[capital,lower,number]
    roll = random.choice(dic)
    s+=roll
    return s
    code = yz(5)
    print(code)

    sys,os模块

    import sys
    import os
    获取当前python解释器的环境变量路径
    print(sys.path)

    将当前项目添加到环境变量中
    BASE_PATH = os.path.dirname(os.path.dirname(file))
    print(BASE_PATH)
    sys.path.append(BASE_PATH)

    print(sys.argv)# 文件名,用户名,密码

    """
    os与操作系统交互的模块
    """
    import os
    需求获得当前的根目录

    先获得当前文件的上一级
    DAY_16PATH = os.path.dirname(file)
    print(DAY_16PATH)

    项目的根目,路径相关的值都用‘常量’
    BASE_PATH =os.path.dirname(DAY_16PATH)
    print(BASE_PATH)

    路径的拼接:拼接文件绝对路径
    TEST_PATH = os.path.join(DAY_16PATH,'写真集.txt')
    print(TEST_PATH)

    判断文件/文件夹是否存在,存在返回Ture,不存在返回False
    print(os.path.exists(TEST_PATH))
    print(os.path.exists(BASE_PATH))

    判断文件夹是否存在,
    print(os.path.isdir(TEST_PATH))
    print(os.path.isdir(DAY_16PATH))

    创建文件
    DIR_PATH = os.path.join(DAY_16PATH,'写真集')#后边是名字,这个只是地址的拼接,并不会产生影响

    os.mkdir(DIR_PATH)

    删除文件,只能删除空文件
    os.rmdir(DIR_PATH)

    yellow_list = os.listdir(r'D:工程python13正式课程11.16写真集')
    print(yellow_list)

    enmerate (可迭代对象)——把列每个元素加上位置索引,用元组包裹

    res = enumerate(yellow_list)
    print(res)
    print(list(res))
    让用户选择文件
    1.打印所有老师的作品
    2.限制用户必须输入数字,数字的范围必须在编号内
    若不是数字,则重新选择
    若是数字,往下走判断是否在编号范围内
    判断如果不在列表范围内,则重新选择
    while True:
    for index, name in enumerate(yellow_list):
    print(f'编号{index}内容{name}')
    choice = input('请输入您的选择,输入编号')
    if not choice.isdigit():
    print('请输入纯数字')
    if choice not in range(len(yellow_list)):
    print('输入序号不存在,请重新输入')
    file_name = yellow_list[int(choice)]
    OPEN_PATH = os.path.join(r'D:工程python13正式课程11.16写真集',file_name)
    with open(OPEN_PATH,'r',encoding='utf8') as f:
    print(f.read())

    hashlib模块

    """
    hashlib是一个加密模块:
    内置了MD5:
    摘要算法:
    ——摘要是从内容中获取的加密字符串
    ——摘要一样,内容就一定一样:保证唯一性
    ——密文密码就是一个摘要

    """

    import hashlib
    md5_obj = hashlib.md5()#固定流程

    str1 = '1234'

    md5_obj.update(str1.encode('utf8'))#update,必须传入bytes类型
    res = md5_obj.hexdigest()#编写密码
    print(res)

    import hashlib

    def pwd_md5(pwd):
    md5_obj = hashlib.md5()
    str1 = pwd
    md5_obj.update(str1.encode('utf8'))

    sal = '雨生好帅'#创造盐
    
    md5_obj.update(sal.encode('utf8'))#加盐
    
    
    res = md5_obj.hexdigest()
    return res
    

    json模块

    主要两组函数,

    dumps&loads 序列化和反序列化

    dump&load节省了f.write和f.read

    import json
    d = {'nanme','tian','age',18}
    json.dumps(d)

    res = json.dumps(d)
    print(res)
    import json
    user_dic ={
    'user':'tank'
    ,'password':123
    }
    with open ('user.json','w',encoding='utf8')as f:
    json.dump(user_dic,f)
    with open('user.json','r',encoding='utf8')as f:
    res = json.load(f)
    print(res)
    print(type(res))
    print(res['user'])

    pickle模块

    与json相比,这个模块的有点在于支持所有python的数据类型转换

    可以直接存bytes类型。存取更加快速。

    缺点是无法跨平台

    collection 模块

    这个模块提供了除了把大数据类型以外的类型

    主要记住两类

    具名元组

    关键字namedtuple

    from collections import namedtuple
    point = namedtuple('坐标',['x','y'])
    p = print(1,2)
    print(p)
    print(type(p))
    p = namedtuple('小电影','city movie name')
    tank_and_sean = p('Tokyo','HOT','小泽')
    print(tank_and_sean)#小电影(city='Tokyo', movie='HOT', name='小泽')

    有序化字典

    关键字:OrderedDict

    from collections import OrderedDict
    order_dict = OrderedDict({'x':1,'y':2,'z':3})
    print(order_dict)
    print(order_dict.get('y'))
    print(order_dict['y'])

    openpyxl模块

    可以对EXCEL进行操作

    写入
    from openpyxl import Workbook
    wb_obj = Workbook()#函数加载进变量
    wb1 = wb_obj.create_sheet('作业',0)
    wb1['a10']=100
    wb_obj.save('作业.xlsx')

    读取更改
    from openpyxl import load_workbook
    wb_obj = load_workbook('作业.xlsx')
    wb2 = wb_obj['作业']
    print(wb2['a10'].value)
    wb_obj.save('作业1.xlsx')

    save,文件存在,在原文件上直接保存,不存在,新建文件夹,存储是覆盖原文件,或者新建一个表格
    

    subprocess模块

    可以通过python代码操作终端发送命令,并可以返回结果

    import subprocess
    while True:
    # 1.让用户输入终端命令
    cmd_str = input('请输入终端命令:').strip()
    # Popen(cmd命令, shell=True,
    # stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    # 调用Popen就会将用户的终端命令发送给本地操作系统的终端
    # 得到一个对象,对象中包含着正确或错误的结果。
    obj = subprocess.Popen(
    cmd_str, shell=True,
    stdout=subprocess.PIPE,
    stderr=subprocess.PIPE
    )

    success = obj.stdout.read().decode('gbk')
    if success:
        print(success, '正确的结果')
    
    error = obj.stderr.read().decode('gbk')
    if error:
        print(error, '错误的结果')
    

    logging模块

    用来记录日志模块,一般记录用户操作
    1.log文件目录

    BASE_PATH = os.path.dirname(os.path.dirname(file))
    logfile_dir = os.path.join(BASE_PATH, 'log_dir')

    2.log文件名

    logfile_name = 'user.log'

    3.log配置字典
    4.
    def get_logger(user_type):
    1.加载log配置字典到logging模块的配置中
    2.获取日志对象
    logger = logging.getLogger(user_type)
    return logger
    logger = get_logger('user')
    logger.info('学习不要浮躁,一步一个脚印!')

    正则模块

    正则表达式:通过符号,从字符串中筛选出你想要的结果

    是一门单独的技术,任何语言都可以使用

    若想使用正则使用RE模块在python中

    findall

    匹配所有字符,拿到返回的结构,返回的结果是一个列表

    search

    匹配一个后直接结束,没有就报错

    返回对象

    match

    从头开始匹配

    返回对象

  • 相关阅读:
    VS开发工具 因插件问题导致 已停止工作 解决办法
    niceScroll 简单使用 及 插件API
    使用JQGrid 问题汇总 不定时更新
    H5特性 MutationObserver 监听元素 动态改变iframe高度
    UVALIVE 3972 March of the Penguins
    Codeforces #105 DIV2 ABCDE
    UVALIVE 3644 X-Plosives
    UVALIVE 3645 Objective: Berlin
    UVALIVE 3031 Cable TV Network
    UVALIVE 2927 "Shortest" pair of paths
  • 原文地址:https://www.cnblogs.com/fxsm/p/11893370.html
Copyright © 2011-2022 走看看