zoukankan      html  css  js  c++  java
  • python(11)---第三方模块

    模块  一个python文件就是一个模块
    有三种模块:
    1、标准模块---不需要你单独安装,python自带的模块 time/os/json/datetime/random....
    2、第三方模块
    3、自己写的python

    安装第三方模块
    1、在线安装   
       pip install xxx
    2、自己下载压缩包安装  
       2.1 .tar.gz结尾的压缩包  先解压,再到目录下安装 
             python  setup.py install
       2.2 .whl 结尾的压缩包
             pip install xxx.whl
    一、random模块
    import random
    print(random.randint(100000,100000000))  #随机取一个整数,包含头和尾   range--顾头不顾尾   可用于随机生成验证码  61407198
    print(random.uniform(1,900)) #随机取一个小数 652.1150991637816
    
    stu=['xiaojun','xinxin','xiuxian','lixin','weiwei','wangying']
    print(random.choice(stu))  #随机取一个元素  传入参数只要可循环即可  string/list/dic/truple/set....
    print(random.sample(stu,3))  #随机取n个元素
    
    list=list(range(1,11))
    print('洗牌前的list:',list)  #洗牌前的list: [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]
    random.shuffle(list) #洗牌 此方法没有返回值  只能传list,因为string和元组不能改变;字典和集合天生就是无序的,不用打乱
    print('洗牌后的list:',list)  #洗牌后的list: [9, 3, 5, 6, 2, 7, 8, 10, 1, 4]

     二、os模块

    import os
    os.rename(old,new)
    #文件重命名 os.remove() #删除文件 os.mkdir('directory') #创建文件夹 父目录不存在会报错 os.mkdir('directory/python') # FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'directory/python' os.makedirs('directory2/python') #创建文件夹 父目录若不存在会先创建父目录 os.removedirs('directory2') #只能删空文件夹 OSError: [WinError 145] 目录不是空的。: 'directory2' print(os.listdir('d:\')) #显示该目录下面的所有文件和文件夹 不传参数时,就显示当前目录下的文件和文件夹 print(os.path.isdir('directory'))#判断是否是文件夹 print(os.path.isfile('os模块.py')) #判断是否是文件 print(os.path.exists('os模块.py')) #判断文件是否存在 os.walk('D:PycharmProjects') #列出目录下所有的文件和文件夹,会递归列出所有子文件夹中的文件 # 用os.walk()统计文件个数 统计d盘下面有多少个python文件 res = os.walk(r'D:PycharmProjects') #r--不转义特殊字符 count=0 for cur_path,dirs,files in res: #循环返回三个参数 c--当前循环的目录 d--当前目录中有哪些文件夹 f--当前目录下有哪些文件 for f in files: if f.endswith('.py'): count+=1 print(count) # 用os.walk方法查找文件 def find_file(path,keyword): res = os.walk(path) for cur_path,dirs,files in res: for file_name in files: if keyword in file_name: print('该文件在%s下面'%cur_path) res=os.system('ipconfig') #执行操作系统命令 只执行命令,没有结果 os.system('dir') 查看当前目录有哪些东西 print('os.system命令返回结果:',res) #os.system命令返回结果: 0 os.popen() #执行操作系统命令 有返回值 需调用reda()方法读取结果 res1= os.popen('ipconfig').read() print('os.popen返回结果:',res1) #os.popen返回结果: Windows IP 配置 ...... os.path.join() #拼接路径 不同的系统会自动匹配不同的路径分隔符 print(os.path.join('china','guangdong','zhuhai')) #chinaguangdongzhuhai print(os.path.split(r'D:PycharmProjectsjnzfor循环.py')) #分割路径和文件名 ('D:\PycharmProjects\jnz', 'for循环.py') print(os.path.dirname(r'D:PycharmProjectsjnzfor循环.py')) #取父目录 (即上一层目录) D:PycharmProjectsjnz print(os.path.getsize(r'D:PycharmProjectsjnzfor循环.py')) #取文件的字节数 327 单位是字节 可用来判断文件是否为空 print(os.getcwd()) #取当前目录 D:PycharmProjectsday4day6 print(os.chdir('D:PycharmProjectsjnz')) #进入到哪个目录下

    三、time模块

    #和时间相关的操作
    import time
    
    # time.sleep(60)  #等待
    
    # 两种表示时间的方式
    #1、格式化好的时间  20180915  14:09:20  便于阅读
    #2、时间戳   从计算机诞生那天到现在过了多少秒,便于计算时间
                 #计算50天后的时间  50*24*60*60 + 当前时间戳
    
    #获取当前格式化时间
    # 年 Y可大写(2018)或小写y(18)  月--m  日--d小写    时--H 分--M 秒--S 都是大写
    # 中间的连接符是自定义的,也可不要
    res=time.strftime('%Y-%m-%d %H:%M:%S')
    print(res)  #2018-09-16 11:26:44
    
    #获取当前时间戳  精确到毫秒(不想要小数点后的内容可以用int()强制转换一下)
    res = time.time()
    print(res)  #1537068404.7712967
    
    #两种时间方式相互转换,需借助时间元组
    
    #一、格式化时间换成时间戳
    # 格式化时间--->时间元组--->时间戳
    time_tuple=time.strptime('2122-01-02 19:23:59','%Y-%m-%d %H:%M:%S') #time.strptime先把格式化好的时间转成时间元组
    res=time.mktime(time_tuple)   #time.mktime()
    print(res)   #2018-09-16 11:33:09
    
    #封装函数---- 将格式化时间换成时间戳
    #不传参数返回当前时间戳
    def str_to_timestamp(time_str=None,format='%Y%m%d%H%M%S'):
        if time_str:
            time_tuple = time.strptime(time_str, format)  # 先把格式化好的时间转成时间元组
            timestamp=time.mktime(time_tuple)
        else:
            timestamp=time.time()
        return int(timestamp)
    
    print(str_to_timestamp())   #1537069232
    print(str_to_timestamp('20561123195940'))  #2742206380
    print(str_to_timestamp('2056-11-23 19:59:40','%Y-%m-%d %H:%M:%S')) #2742206380
    
    
    #时间戳转换成格式化时间
    #时间戳--->时间元组--->格式化时间
    # time_tuple=time.gmtime(time.time()) #把当前时间戳转时间元组,标准时区
    # time_tuple=time.localtime(time.time()) #把当前时间戳转时间元组,当前时区
    time_tuple=time.gmtime(98765433) #把时间戳转时间元组,当前时区
    res2 = time.strftime('%Y-%m-%d %H:%M:%S',time_tuple)
    print(res2)  #1973-02-17 02:50:33
    
    #封装函数----时间戳转换成格式化时间
    #如果不传时间戳的话,那么久返回当前格式化时间
    def timestamp_to_strtime(timestamp=None,format='%Y-%m-%d %H:%M:%S'):
        if timestamp:
           time_tuple= time.localtime(timestamp)
           str_time=time.strftime(format, time_tuple)
        else:
            str_time=time.strftime(format)
        return str_time
    
    fifty = str_to_timestamp()+50*365*24*60*60
    res =timestamp_to_strtime(fifty)
    print('50年后的时间是%s'%res)   #50年后的时间是2068-09-03 11:53:20

    四、hashlib加密模块

    import hashlib
    
    password='123456'
    pwd=password.encode()  #字符串转成二进制类型才能加密  b'123456'
    
    m = hashlib.md5(pwd)   #md5加密方式 一般都用md5加密
    # m = hashlib.sha1(pwd)  #其他加密方式   密码长度更长,更安全
    # m = hashlib.sha224(pwd)
    # m = hashlib.sha256(pwd)   
    print(dir(m))  #模块中有哪些方法  dir()方法可以查看该模块有哪些方法
    print(m.hexdigest())  #e10adc3949ba59abbe56e057f20f883e  MD5加密后的密码都是32位的(不管加密前有多长)
    
    #MD5加密是不可逆的  即加密后不能再解密到明文
    
    # 撞库---将常见简单密码加密后的结果保存起来,和明文对应
    
    #加盐
    #明文密码 + 随机产生一个字符串    然后再加密
    
    #封装函数---用MD5加密
    def my_md5(s,salt=None):
        s =str(s)
        if salt:
            s=s+salt
        m=hashlib.md5(s.encode())
        return m.hexdigest()

    五、第三方模块

        (1)xpinyin模块

    import xpinyin
    
    s=xpinyin.Pinyin()  #实例化
    print(s.get_pinyin('山竹来啦'))  #shan-zhu-lai-la   默认用-把每个拼音连接
    print(s.get_pinyin('山竹来啦',''))  #shanzhulaila

     (2)pymysql模块

    import pymysql
    
    host ='118.24.3.40'
    user ='jxz'
    password='123456'  #密码只能是字符串类型
    db='jxz'
    port = 3306   #端口号只能写int类型
    charset ='utf8' #只能写utf8   防止插入数据库时出现乱码
    
    #建立连接
    conn=pymysql.connect(host=host,password=password,user=user,db=db,port=port,charset=charset,autocommit=True)
    #建立游标
    cur =conn.cursor()
    sql='select * from app_myuser limit 5;'
    cur.execute(sql)  #只执行sql语句,不返回结果
    # print(cur.description) #获取表结构信息(表里有哪些字段及字段类型...)
    print(cur.fetchall()) #获取sql执行后得到的所有结果 返回结果是一个二维数组,每一条数据都是数据库里的一条记录; cur.fetchall(cursor=pymysql.cursors.DictCursor),返回list,list里面是一个个字典,每一条数据一个字典
    #((1145, 'liuyana001', '123456', 1), (1146, 'xd', '123456', 1), (1147, '颜无柳', '1', 1), (1148, 'pythonnjf', '123456', 1), (1149, 'gebilaowang', '123456', 1))
    # print(cur.fetchone()) #获取sql执行后得到的一条结果  (1145, 'liuyana001', '123456', 1)
    
    # sql='insert into app_myuser(username,passwd,is_admin) VALUE ("hahaha","456789","0") '
    # cur.execute(sql)
    # conn.commit() #select、update需要commit提交  或者在conn中添加 autocommit=True自动提交
    
    cur.close()   #执行完sql后必须关闭连接
    conn.close()
    
    # 封装函数---连接数据库
    def my_db(ip,user,password,db,sql,port=3306,charset='utf8'):
        conn = pymysql.connect(host=ip, password=password, user=user, db=db, port=port, charset=charset, autocommit=True)
        cur=conn.cursor()
        cur.execute(sql)
        res =cur.fetchall()
        cur.close()
        conn.close()
        return res

    (3) xlwt、xlrd、xlutils模块

    import xlwt,xlrd,xlutils
    
    #写Excel
    
    book=xlwt.Workbook()
    sheet= book.add_sheet('sheet1')
    sheet.write(0,0,'id')    #0行0列   id
    sheet.write(0,1,'username')  #0行1列  username
    sheet.write(0,2,'password')  #0行2列  passname
    
    sheet.write(1,0,'1')
    sheet.write(1,1,'hahaha')
    sheet.write(1,2,'123456')
    
    sheet.write(2,0,'2')
    sheet.write(2,1,'lihui')
    sheet.write(2,2,'123456')
    book.save('stu.xls')
    
    stus = [
        [1,'njf','1234'],
        [2,'xiaojun','1234'],
        [3,'hailong','1234'],
        [4,'xiaohei','1234'],
        [4,'xiaohei','1234'],
        [4,'xiaohei','1234'],
        [4,'xiaohei','1234'],
        [4,'xiaohei','1234'],
        [4,'xiaohei','1234'],
    ]
    
    #循环往Excel表中写内容 2层循环
    row=0  #控制行
    for stu in stus:
        colum = 0  #控制列
        for i in stu:
            sheet.write(row,colum,i)
            colum+=1
        row+=1
    book.save('stu.xls')    #最后要保存  excel文件名要以xls结尾,xlsx微软打不开
    
    #用emumerate()函数
    for row ,data in enumerate(stus):
        for col ,val in enumerate(data):
           sheet.write(row,col,data)
    book.save('stu.xls')
    
    #读Excel
    book = xlrd.open_workbook('stu.xls')
    sheet = book.sheet_by_index(0) #根据下标编号获取Excel
    sheet = book.sheet_by_name('sheet1') #根据sheet名称获取sheet
    print(sheet.nrows)  #excel里面有多少行
    print(sheet.ncols)  #excel里面有多少列
    
    print(sheet.cell(0,0).value) #获取到指定单元格的内容
    print(sheet.cell(0,1).value) #获取到指定单元格的内容
    
    print(sheet.row_values(0))  #获取到整行的内容
    print(sheet.col_values(0))  #获取到整列的内容
    
    #循环打印Excel中每行的内容
    for i in range(sheet.nrows):
        print(sheet.row_values(i))
    
    
     #修改Excel
    from xlutils import copy
    
    book = xlrd.open_workbook('stu.xls')  #1、现有xlrd打开一个Excel
    new_book = copy.copy(book) #2、用xlutils中的copy功能,复制一个excel
    sheet =new_book.get_sheet(0) #获取sheet页
    sheet.write(0,1,'小白')
    sheet.write(2,0,'小军')
    new_book.save('stu.xls')

     (4)itsdagerous模块

     cookie和session保存在内存中保存和取出时需要操作数据库redis,效率低;

    用itsdangerous模块不需要保存

    import  itsdangerous
    
    salt='$Sdfht'
    t = itsdangerous.TimedJSONWebSignatureSerializer(salt,expires_in=30)
    # salt 加盐; expires_in  超时时间
    
    #加密
    res = t.dumps({'maxiaoma':'machenxi','user_id':1})
    token = res.decode()
    print(token)
    
    # 解密
    res=t.loads('eyJhbGciOiJIUzUxMiIsImlhdCI6MTU0MTgyMDAxNCwiZXhwIjoxNTQxODIwMDQ0fQ.eyJ1c2VyX2lkIjoxLCJtYXhpYW9tYSI6Im1hY2hlbnhpIn0.hrEFz5Z4iJLOdDNVsridqY1hdb5lbWmj6gLY-kVAC8vtVj0ZqaX_SehWTG4eC8RkgFpMZ3hwiDsdaG8XLDWXVw')
    print(res)

     (5) glob模块

          用于过滤出符合特定规则的文件路径名,跟使用windows下的文件搜索差不多

          glob.glob 返回所有匹配的文件路径列表,它只有一个参数pathname,定义了文件路径匹配规则,这里可以是绝对路径,也可以是相对路径。

    import glob
    #打印出 D:PycharmProjectsday4 文件夹下所有的python文件的路径,返回的是一个list
    
    print(glob.glob(r'D:PycharmProjectsday4*.py'))  
    
    # ['D:\PycharmProjects\day4\productManage.py', 'D:\PycharmProjects\day4\t.py']
  • 相关阅读:
    查看mysql版本的四种方法及常用命令
    newInstance和new的区别(good)
    Citrix 服务器虚拟化之六 Xenserver虚拟机创建与快照
    Java实现 蓝桥杯 算法训练 排序
    Java实现 蓝桥杯 算法训练 排序
    Java实现 蓝桥杯 算法训练 排序
    Java实现 蓝桥杯 算法训练 2的次幂表示
    Java实现 蓝桥杯 算法训练 2的次幂表示
    Java实现 蓝桥杯 算法训练 前缀表达式
    Java实现 蓝桥杯 算法训练 前缀表达式
  • 原文地址:https://www.cnblogs.com/HathawayLee/p/9632874.html
Copyright © 2011-2022 走看看