• 自动化学习-Day06


    安装第三方模块的方式:
            1、pip install xxxx
            2、.whl
                pip install c:/user/niuhanyang/desktop/xxx.whl
            3、.tar.gz
                1、先解压
                2、解压之后在命令行里面进入到这个目录下
                3、执行python setup.py install
    
        python3.5 -m pip insatll xxx
    
        python2 -m pip insatll xxx
    
        python3.6 -m pip insatll xxx
    import 模块顺序:
        1、从当前目录下找该文件
        2、从环境变量的目录里面找
    导入模块的实质是什么:
        就是把这个python文件从头到尾执行一次

    #手动添加环境变量
    import sys print(sys.path) sys.path.append(r'D:day06') print(sys.path)

    列表生成式

    res = []
    for i in range(1,34):
        res.append(str(i).zfill(2))
    print(res)
    
    res = [str(i).zfill(2) for i in range(1,34)]
    print(res)
    l = [i for i in range(10)]
    print(l)
    import random
    all_red_ball = [str(i).zfill(2) for i in range(1, 34)]
    all_blue_ball = [str(i).zfill(2) for i in range(1, 17)]
    def gen_seq():
        blue = random.choice(all_blue_ball)
        red = random.sample(all_red_ball,6)
        red = ' '.join(red)
        return '红球:%s 篮球:%s'%(red,blue)
    all_seq=set()
    num = int(input('请输入要产生多少条双色球:').strip())
    while len(all_seq) != num:
        # res = gen_password1()+'
    '
        res = gen_seq()+'
    '
        #xbA17
    
        all_seq.add(res)
    with open('passwords.txt','w',encoding='utf-8') as fw:
        fw.writelines(all_seq)

    OS模块

    import os
    os.rename(old,new)#重命名
    os.remove(f)#删除文件
    
    os.mkdir('china/beijing') #创建文件夹
    os.makedirs('china/beijing') #父目录不存在的时候会帮你创建
    os.removedirs('china')#只能删除空文件夹
    
    print(os.listdir())#显示该目录下面的所有文件和文件夹
    print(os.path.isdir('china1'))#判断是否是文件夹
    print(os.path.isfile('china'))#判断是否是文件
    print(os.path.exists('china'))#判断文件或者文件夹是否存在
    res
    = os.system('ipconfig')#执行操作系统命令 ls] print('res...',res) res = os.popen('ipconfig').read()#用来执行操作系统命令 print(res)
    print(os.path.join(
    'china','beijing','haidian','changping','a.py'))#拼路径 res = os.path.split(r'chinaeijinghaidianchangpinga.py')#用来分割文件名和路径 print(res)
    res
    = os.path.dirname(r'chinaeijinghaidianchangpinga.py')#取父目录 print(res) print(os.path.getsize('笔记.txt'))#单位是字节 print(os.getcwd())#取当前的目录 print(os.chdir(r'C:Users hyPycharmProjectsjnzday5'))#进入到哪个目录下 print(os.getcwd())#取当前的目录

    统计目录下有多少个指定类型文件

    import os
    res = os.walk(r'china')
    count = 0
    for cur_path, dirs, files in res:
        print(cur_path)
        for f in files:
            if f.endswith('.py'):
                count += 1
                os.remove(os.path.join(cur_path,f))
    print(count)
    import os
    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)
    
    find_file(r'C:\','9e7aaf5865c7eb142addd44ffeb11eeb938140e6211dfbca9cd9463c5cc67113.png')

    time模块

    import time
    res = time.strftime('%Y-%m-%d %H:%M:%S') #取当前的格式化日期
    res = time.time()#获取当前的时间戳
    
    #将时间转回时间戳
    time_tuple = time.strptime('2038-08-29 19:23:59','%Y-%m-%d %H:%M:%S')#把格式化好的时间转成时间元组
    print(time.mktime(time_tuple))
    
    
    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)
    
    res = time.localtime(time.time())#是把时间戳转时间元组的,当前时区
    res2 = time.strftime('%Y-%m-%d %H:%M:%S',res)
    print(res2)
    
    
    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
    
    
    #用当前的时间戳+50年的秒数,时间戳转成格式化好的时间
    
    five = str_to_timestamp() - (5*24*60*60)
    res = timestamp_to_strtime(five)
    print('50年后的时间是',res)

    第三方模块

    import xpinyin
    s = xpinyin.Pinyin()
    pinyin = s.get_pinyin('你好','')
    print(pinyin)
    import pymysql
    conn = pymysql.connect(host=host,password=password,
                    user=user,db=db,port=port,
                    charset=charset,autocommit=True
                    )#建立连接
    
    cur= conn.cursor() #建立游标
    cur.execute()#只是帮你执行sql语句
    print(cur.fetchall())#获取数据库里面的所有的结果
    print('fetchone',cur.fetchone())
    sql='insert into app_myuser (username,passwd,is_admin) VALUE ("python123456","123456",1);'
    sql='select * from app_myuser limit 5;'
    cur.execute(sql)
    print(cur.description)#获取这个表里面的所有字段信息
    conn.commit()#提交
    cur.close()
    conn.close()
    def my_db(ip,user,password,db,sql,port=3306,charset='utf8'):
        conn = pymysql.connect(
            host=ip,user=user,password=password,
            db=db,
            port=port,charset=charset,autocommit=True
        )
        cur = conn.cursor()
        cur.execute(sql)
        res = cur.fetchall()
        cur.close()
        conn.close()
        return res
    
    def my_db2(sql):
        conn = pymysql.connect(
            host='118.24.3.40',user='jxz',password='123456',
            db='jxz',
            port=3306,charset='utf8',autocommit=True
        )
        pass

    hashlib加密模块

    import hashlib
    password='123123'
    print(password.encode())#转成二进制类型的才可以加密
    m = hashlib.md5(password.encode())
    print(m.hexdigest())
    
    def my_md5(s:str,salt=None):
        #salt是盐值
        s = str(s)
        if salt:
            s = s+salt
        m = hashlib.md5(s.encode())
        return m.hexdigest()

    Excel操作

    #读Excel
    import xlrd
    
    book = xlrd.open_workbook('stu.xls')
    sheet = book.sheet_by_index(0)
    # sheet = book.sheet_by_name('sheet1')
    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))#获取到整行的内容
    
    for i in range(sheet.nrows):#循环获取每行的内容
        print(sheet.row_values(i))
    #写Excel
    import xlutils
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    sheet.write(0,0,'id')#指定行和lie写内容
    sheet.write(0,1,'username')
    sheet.write(0,2,'password')
    
    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'],
    ]
    line = 0 #控制的是行
    for stu in stus:#
        col = 0
        for s in stu:
    
            sheet.write(line,col,s)
            col+=1
        line+=1
    
    book.save('stu.xls')# .xlsx
    #修改Excel
    
    import xlrd
    from xlutils import copy
    book = xlrd.open_workbook('stu.xls')
    #先用xlrd打开一个Excel
    new_book = copy.copy(book)
    #然后用xlutils里面的copy功能,复制一个Excel
    sheet = new_book.get_sheet(0)#获取sheet页
    sheet.write(0,1,'')
    sheet.write(1,1,'')
    new_book.save('stu.xls')

    生成密码

    import random
    import string
    
    def gen_password1():
        pwd_len = random.randint(8,16)
        upper = random.sample(string.ascii_uppercase,1)
        lower = random.sample(string.ascii_lowercase,1)
        digit = random.sample(string.digits,1)
        punctuation = random.sample(string.punctuation,1)
        other = random.sample(string.ascii_letters+string.digits+string.punctuation
                      ,pwd_len-4)
        res = upper+lower+digit+punctuation+other
        random.shuffle(res)
        return ''.join(res)
    
    def gen_password2():
        pwd_len = random.randint(8,16)
        all_str = string.ascii_letters+string.digits+string.punctuation
        res = set(random.sample(all_str,pwd_len))
        if res & set(string.ascii_lowercase) and res & set(string.digits) 
             and res & set(string.ascii_uppercase) and res & set(string.punctuation):
            return ''.join(res)
        return gen_password2()
    
    
    
    all_passwords=set()
    num = int(input('请输入要产生多少条密码:').strip())
    while len(all_passwords) != num:
        # res = gen_password1()+'
    '
        res = gen_password2()+'
    '
        #xbA17
    
        all_passwords.add(res)
    with open('passwords.txt','w',encoding='utf-8') as fw:
        fw.writelines(all_passwords)
  • 相关阅读:
    Android 解析内存泄漏
    Maven--几个需要补充的问题(三)
    android编程——百度地图初探
    poj 2752 Seek the Name, Seek the Fame(KMP需转换下思想)
    android面试题之二
    (3)选择元素——(2)文档对象模型(The Document Object Model)
    Tiny4412汇编流水灯代码,Tiny4412裸机LED操作[1]
    A9裸机
    2.1 linux中uboot移植
    芯片结构
  • 原文地址:https://www.cnblogs.com/rongpeng/p/12017293.html
Copyright © 2020-2023  润新知