• day06数据库、发送邮件、操作excel等


    一、作业分析

    1.删除日志

    '''
    作业:
    1、写一个删除日志的脚本,把三天前的日志并且为空的日志删除
    分析
    1.获取当前文件路径、文件名等信息
    2.循环文件
    3.判断文件为空,删除
    4.判断文件是3天前的文件,删除
    5.删除空文件夹
    '''

    import os,time
    #3天前的日期
    day = 60 * 60 * 24 * 3
    #把日期变成时间戳
    def str_to_timestamp(str_time,format = '%Y-%m-%d'):
    time_tuple = time.strftime(str_time,format)
    return int(time.mktime(time_tuple))

    # print(str_to_timestamp('2019-07-31'))

    def clean_log(path):
    #是否是一个目录
    if os.path.isdir():
    #walk获取路径、文件名、文件夹
    for cur_path,dirs,files in os.walk(path):
    for file in files:
    #判断后缀是否有.log
    if file.endswith('.log'):
    #android_2020-09-02.log
    #a.log
    try:
    file_time = file.split('.')[0].split('_')[-1]
    except Exception as e:
    print('%s不是标准的日志文件,不处理'%file)
    else:
    file_time_stamp = str_to_timestamp(file_time)
    ago_time_stamp = time.time() - day
    file_abs_path = os.path.join(cur_path,file)
    if file_time_stamp < ago_time_stamp or os.path.getsize(file_abs_path) == 0:
    if time.strftime('%Y-%m-%d') in file:
    continue
    os.remove(file_abs_path)

    else:
    print('路径错误!')

    clean_log('log')

    2.双色球

    '''
        2、写一个产生双色球号码的程序,输入几就产生多少条
            1、每次产生的里面不能有重复的
            2、产生的号码要 1 2 3 4 5 6  7
            1-32
            1-17
            01 02 03 04 05 06 07
    红球一共6组,每组从1-33中抽取一个,六个互相不重复。然后蓝球是从1-16中抽取一个数字,这整个组成的双色球
    
    分析
    1.随机获取6个不同的数字,并且把一位的前面+0
    2.随机获取1个数字,并且把一位的前面+0
    3.组合6+1
    4.循环输入的次数
    '''
    
    import random
    # number = input('number:').strip()
    # if number.isdigit() and int(number)>0:
    #
    #     l = []
    #     while True:
    #         red = random.sample(range(1,34),6)
    #         red.sort()
    #         blue = random.sample(range(1,18),1)
    #         result = red + blue
    #         result = [str(ball).zfill(2) for ball in result]
    #         seq = ' '.join(result)
    #         if seq not in l:
    #             l.append(seq)
    #             print('生成的双色球号码是:红球:%s 篮球是:%s' %(' '.join(result[:6]),result[-1]))
    #         if int(number) == len(l):
    #             break
    
    reds = [str(ball).zfill(2) for ball in range(1,34)]
    blues = [str(ball).zfill(2) for ball in range(1,18)]
    
    number = input('number:').strip()
    if number.isdigit() and int(number)>0:
        l = set()
        while int(number) != len(l):
            red = random.sample(reds,6)
            red.sort()
            blue = random.sample(blues,1)
            result = red + blue
            result = [str(ball).zfill(2) for ball in result]
            seq = ' '.join(result) + '
    '
            l.add(seq)
            print('生成的双色球号码是:红球:%s 篮球是:%s' %(' '.join(result[:6]),result[-1]))
    
    with open('seq.txt','w',encoding='utf-8') as fw :
        fw.writelines(l)

    二、发送邮件

    import yamail#上传到了pip源
    import yagmail#发送附件,附件如果是中文名,显示乱码
    
    smtp = yamail.SMTP(
                       host ='smtp.qq.com',
                       user='xxxxx@qq.com',
                       password='授权码'
    )#如果是163、qq等免费邮箱的话需要授权码,自己公司的邮箱,一般都使用
    
    smtp.send(to = 'xxxxxxx@qq.com',#发送给谁,多个人写list
              subject = '请查收',#邮件标题
              # cc = '',#抄送,如果是多个人list
              contents='邮件正文',#邮件正文
              attachments = '笔记'#笔记必须在当前路径下存在或者写出绝对路径
              )#附件,多个写list
    smtp.close()

    三、异常处理

    (1)单独的异常判断

    a = [1,2,3]
    try:
        # a[4]
        a[2]
        2/0
    except IndexError as e:
        print(e)
        print('出错了')
    # open('fd.txt')
    # float('s.3')
    
    except ZeroDivisionError as e:
        print('除数不能为0')
    
    #TypeError,KeyError找不到字典的key
    #FileNotFoundError:文件打不开
    except TypeError as e:
        print('类型错误')
    except KeyError as e:
        print('找不到字典的key')
    except FileNotFoundError as e :
        print('文件打不开')

    (2)Exception包含所有的异常

    a = [1,2,3]
    try:
        # a[4]
        a[2]
    except Exception as e:
        print('出异常了',e)
    else:
        print('没有异常了')
    finally:#不是必须写的
        print('aaa')

    (3)使用finally的场景:就算异常或者不异常都会关闭文件

    f = open('xxx','w')
    try:
        f.write()
    except:
        print('异常')
    else:
        print('xxx')
    finally:
        f.close()

    (4)traceback:会打印出错误信息,不会使程序停止

    import traceback
    def is_price(s):
        try:
            f = float(s)
        except Exception as e:
            #错误直接打印出来使用
            # traceback.print_exc()
            #错误文件报错到文件或者数据库使用
            print('自己加的',traceback.format_exc())
            # print(e)
            return False
            # print('请输入正确的小数')
        else:
            if f > 0:
                return True
    is_price('sdfsdaf')
    #调用堆栈信息

    结果:

     四、sys模块

    import sys,os
    sys.version
    sys.platform#操作系统平台
    sys.path
    sys.path_hooks
    
    print(sys.argv)#用来获取运行python文件的时候,传过来的参数,list
    #python sys模块.py
    #python product.py create_user    python文件参数后传参数
    
    command = sys.argv[1]
    if command == 'install':
        model_name = sys.argv[2]
        print('install %s'%model_name)
    elif command == 'freeze':
        os.system('pip install freeze')
    else:
        print('目前只支持install 和 freeze')
    
    #备份数据的功能 IP user password db
    os.system('python bak_db.py 118.23.4.30 root 123456 test')
    #python bak_db.py 118.23.4.30 root 123456 test
    #python tools.py clean_log

    五、excel表格

    (1)读取excel ====xlrd

    import xlrd
    
    book = xlrd.open_workbook('students.xls')
    
    # sheet = book.sheet_by_index(0)
    sheet = book.sheet_by_name('sheet1')
    print(book.sheets())#所有的sheet页,返回的是一个list,list里面就是每个sheet的对象
    for s in book.sheets():
        s.row_values(2)
    
    print('111',sheet.cell(0,0).value)#读取第一行,第一列
    print(sheet.row_values(0))#读取第一行
    print(sheet.row_values(1))#读取第二行
    
    print(sheet.col_values(0))#读取第一列
    print(sheet.col_values(1))#读取第二列
    
    print(sheet.nrows)#多少行
    print(sheet.ncols)#多少列

    (2)写入excel===xlwt

    import xlwt
    
    # book = xlwt.Workbook()
    # sheet = book.add_sheet('students')
    #
    # sheet.write(0,0,'id')
    # sheet.write(0,1,'name')
    # sheet.write(0,2,'age')
    #
    # sheet.write(1,0,'1')
    # sheet.write(1,1,'fd')
    # sheet.write(1,2,'18')
    # book.save('students.xls')#如果后缀携程xlsx,使用微软的office打不开
    ==================================
    #编号 姓名 地址 年龄
    
    #
    stus = [
        [1,'ds','bejing',51],
        [2,'fd','shanghai',28],
        [3,'zc','shanghai',16],
        [4,'lhy','shanghai',21],
        [5,'ylm','shanghai',35],
        [6,'wxl','beijing',16],
    ]
    =====================================
    方法一:
    # stus.insert(0,['编号','姓名','地址','年龄'])
    # book = xlwt.Workbook()
    # sheet = book.add_sheet('sheet1')
    #
    # row = 0
    # for stu in stus:#控制行
    #     col = 0
    #     for s in stu:#控制列
    #         sheet.write(row,col,s)
    #         col += 1
    #     row += 1
    # ages = [s[-1] for s in stus if type(s[-1])!=str]
    # avg_age = round(sum(ages)/len(ages),2)
    # content= '平均年龄:%s'%avg_age
    # sheet.write(row,0,content)
    #
    # book.save('students.xls')
    
    =====================================
    方法二:
    #enumerate()#枚举
    # l= ['a','b','c']
    # for index,item in enumerate(l,1):
    #     print('%s=>%s'%(index,item))#下标+元素组成的元组
    
    stus.insert(0,['编号','姓名','地址','年龄'])
    book = xlwt.Workbook()
    sheet = book.add_sheet('sheet1')
    
    
    for row,stu in enumerate(stus):#控制行
        for col,s in enumerate(stu):#控制列
            sheet.write(row,col,s)
    ages = [s[-1] for s in stus if type(s[-1])!=str]
    avg_age = round(sum(ages)/len(ages),2)
    content= '平均年龄:%s'%avg_age
    sheet.write(row+1,0,content)
    
    book.save('students.xls')

    (3)修改excel=====xlutils

    from xlutils import copy#修改中的复制
    import xlrd#读取文件
    
    book = xlrd.open_workbook('students.xls')
    sheet = book.sheet_by_index(0)
    new_book = copy.copy(book)#复制一份
    # print(dir(new_book))
    copy_sheet = new_book.get_sheet(0)
    for row in range(1,sheet.nrows-1):
        addr = sheet.cell(row,2).value
        addr = addr.replace('beijng',"北京").replace('shanghai',"上海")
        copy_sheet.write(row,2,addr)
    
    new_book.save('students.xls')

    结果:

    六、操作数据

    import pymysql
    
    host = '118.24.3.40'
    user = 'jxz'
    password = '123456'#字符串
    db = 'jxz'
    port = 3306#int类型
    
    connect = pymysql.connect(host=host,user=user,
                              password=password,
                              port=port,db=db,
                              autocommit=True)#AUTOCOMMIT设置后自动提交,不需要使用connect.commit()
    # cur = connect.cursor()#建立游标,仓库管理员
    cur = connect.cursor(pymysql.cursors.DictCursor)#返回的数据为字典
    # cur.execute('insert into students(name,class) VALUES ("fd","tmz")')
    # cur.execute('insert into students VALUES (101,"fd","女",18,"tianma","北京")')
    # cur.execute('delect from students where id =1')
    # cur.execute('updat students set name="fd" where id = 20;')
    cur.execute('select * from students limit 5;')
    # cur.execute('select * from students where id = 1;')
    print('description',cur.description)#表的描述
    
    # connect.rollback()#回滚
    # connect.commit()#提交
    # # result = cur.fetchall()#拿到所有结果,一般只有select的时候使用
    # # print(result)
    # print('fetchmany',cur.fetchmany(3))#返回指定的条数
    # print('fetchone',cur.fetchone())#返回单个的元组,也就是一条记录(row),如果没有结果 则返回 None
    
    # for data in cur:
    #     print(data)
    
    cur.close()#关闭游标
    connect.close()

    遇到问题:

    如果在pycharm中使用pip安装数据库,出现下图问题:

    解决方法:加环境变量python.exe和script目录都要加入

     或者可以在网站下载下来安装:如图:

    下载下来两个安装包

    安装方法:

    1.whl的直接pip install 就可以了

    2.解压,出现文件夹,setup.py

     

     模块说明:

    1.安装模块
        第三方安装 pip install xx
                 pip install xxx.whl
                python setup.py install
        卸载:pip uninstall xxx
        升级更新:pip install -U xxxx
                pip install --upgrade xxxx
    2.导入模块
    import xxx
    from xx import xx
    
    3.查找模块原理
    顺序:
    1.当前的目录下
    2.python环境变量目录下
    sys.path
  • 相关阅读:
    【多线程】工具类汇总
    【JVM】GC日志样例解读
    【Docker】
    XXS level5
    XXS level4
    XXS level3
    XXS level2
    SQLI DUMB SERIES-6
    SQLI DUMB SERIES-5
    XXS level1
  • 原文地址:https://www.cnblogs.com/victory-0315/p/13586962.html
Copyright © 2020-2023  润新知