• day16


    day 16 笔记

    模块

    定义模块时可以把一个py文件或一个文件夹(包)当作一个模块,以方便于以后其他py文件的调用。

    对于包的定义:

    • py2:文件见中必须有 _ _init _ _.py 。

    • py3:不需要 _ init _.py .

    推荐大家以后写代码时,都要加上此文件。

    1.模块的调用

    # import 模块 模块.函数()
    import requests
    # from 模块 import 函数 函数() 【as起别名 / *】
    from b4s import *
    # from 模块 import 函数 as 别名 别名()
    fron bs4 import BeautifulSoup as s
    '''
    lizohng
    - jd.py
      - pdd.py
      - tb.py
    包.py
    '''
    import lizhong.jd
    lizhong.jd.f1()

    from lizhong import jd
    jd.f1()

    from lizhong.jd import f1
    f1()

    # 模块和要执行的py文件在同一目录 且 需要 模块中的很多功能时,推荐用: import 模块
    # 其他推荐:from 模块 import 模块 模块.函数()
    # 其他推荐:from 模块.模块 import 函数 函数()

    2.内置模块

    2.1 os

    2.2 sys

    2.3 time

    2.4 json

    2.4.1 dumps

    2.4.2 loads

    2.4.3 注意 如果字典或列表中有中文,序列化时想保留中文

    import json
    v={'name':'alex','age':18,'cname':'金角大王'}
    v1=json.dumps(v)
    print(v1)   # {"name": "alex", "age": 18, "cname": "u91d1u89d2u5927u738b"}

    v2=json.dumps(v,ensure_ascii=False)
    print(v2)   # {"name": "alex", "age": 18, "cname": "金角大王"}

    2.4.4 dump

    import json
    v={'name':'alex','age':18,'cname':'金角大王'}
    with open ('json.txt',mode='w',encoding='utf-8') as file:
       v1=json.dump(v,file)  # 直接写入文件,json类型的字符串 {"name": "alex", "age": 18, "cname": "u91d1u89d2u5927u738b"}
       print(v1)

    2.4.5 load

    import json
    with open ('json.txt',mode='r',encoding='utf-8') as file:
       v1=json.load(file) # 直接读取
       print(v1,type(v1)) # {'name': 'alex', 'age': 18, 'cname': '金角大王'} <class 'dict'>

    2.5 haslib

    2.6 random

    2.7 getpass

    2.8 shutil

    2.9 copy

    2.10 pickle

    ···json,优点:所有语言通用;缺点:只能序列化基本的数据类型 list/dict/int...

    ···pickle,优点:python中所有的东西都能被他序列化(socket对象);缺点:序列化的内容只有python认识。

    2.10.1 dumps 和 loads

    import pickle
    info = {1,2,3,4}
    v1=pickle.dumps(info)
    print(v1)   # b'x80x04x95 x00x00x00x00x00x00x00x8fx94(Kx01Kx02Kx03Kx04x90.'
    v2=pickle.loads(v1)
    print(v2)   # {1, 2, 3, 4}
    # dumps 和 loads 的功能与json相似,只是可以处理的数据类型更多,几乎所有的数据类型都能被序列化,产生pickle自己的数据

    2.10.2 dump 和 load

    import pickle
    info = {1,2,3,4}
    with open ('pickle.txt',mode='wb') as file:
       v=pickle.dump(info,file)   # 写入的是二进制

    with open ('pickle.txt',mode='rb') as file:
       v1=pickle.load(file)
       print(v1)   # {1, 2, 3, 4}

    2.11 shutil

    import shutil

    # 删除目录
    # shutil.rmtree('test')

    # 重命名
    # shutil.move('test','ttt')

    # 压缩文件
    # shutil.make_archive('zzh','zip','D:codes21day16lizhong')

    # 解压文件
    # shutil.unpack_archive('zzh.zip',extract_dir=r'D:codexxxxxxxxxx',format='zip')
    import shutil
    info = r'D:YU PHOTOS'
    shutil.make_archive('new_file','zip',info) # 文件名 格式 需要压缩的文件路径
    
    shutil.unpack_archive(r'C:UsersUsherDesktophomeworkday16
    ew_file.zip',r'C:UsersUsherDesktophomeworkday16lev1lev2','zip') # 要解压的文件路径 需要解压到的路径 格式
    import os
    import shutil
    from datetime import datetime
    ctime = datetime.now().strftime('%Y-%m-%d-%H-%M-%S') # 时间格式化 变成字符串
    
    # 1.压缩lizhongwei文件夹 zip
    # 2.放到到 code 目录(默认不存在)
    # 3.将文件解压到D:x1目录中。
    
    if not os.path.exists('code'): # 如果不存在此目录
        os.makedirs('code') # 创建此目录
    shutil.make_archive(os.path.join('code',ctime),'zip','D:codes21day16lizhongwei')
    # 文件名(目录+时间格式化) 格式 需要压缩的文件路径
    file_path = os.path.join('code',ctime) + '.zip'  # 压缩文件 的 文件路径
    shutil.unpack_archive(file_path,r'D:x1','zip')

    2.12 time 和 datetime

    UTC/GMT:世界时间

    本地时间:本地时区的时间。

    2.12.1 time 模块

    import time
    time.time() # 时间戳 从格林威治时间 1970年1月1日 算起的多少秒
    time.sleep(1) # 等待时间长度
    time.timezone() # 时区

    2.12.2 datetime 模块

    from datetime import datetime,timezone,timedelta
    
    # ##### 获取datetime格式时间 #####
    v1=datetime.now()
    print(v1) # 2020-05-12 18:21:10.704385
    v2=timezone(timedelta(hours=7)) # 东七区 UTC+07:00
    v3=timezone(timedelta(hours=-7)) # 西七区 UTC-07:00
    print(datetime.now(v2)) # 东七区时间 2020-05-12 17:21:10.727391+07:00
    print(datetime.now(v3)) # 西七区时间 2020-05-12 03:21:10.729390-07:00
    
    # ##### 把datetime格式转换成字符串 #####
    v1=datetime.now()
    print(v1,type(v1)) # 2020-05-12 18:24:21.681545 <class 'datetime.datetime'>
    V2=v1.strftime('%Y-%m-%d %H-%M-%S') # 转换成的格式,中间的连接符可以自定义
    print(V2,type(V2)) # 2020-05-12 18-24-21 <class 'str'>
    
    # ##### 字符串转成datetime #####
    v1='2020/05/20 20/00/00'
    v2=datetime.strptime(v1,'%Y/%m/%d %H/%M/%S') # 列出字符串的格式,方便电脑读取
    print(v2,type(v2)) # 2020-05-20 20:00:00 <class 'datetime.datetime'>
    
    # ##### datetime时间的加减 #####
    v1='2020/05/20 20/00/00'
    v2=datetime.strptime(v1,'%Y/%m/%d %H/%M/%S')
    v3=v2-timedelta(days=20) # 减20天
    v4=v2+timedelta(weeks=5) # 加5周
    v5=v2-timedelta(hours=20) # 减20小时
    info1=v3.strftime('%Y-%m-%d %H-%M-%S')
    info2=v4.strftime('%Y-%m-%d %H-%M-%S')
    info3=v5.strftime('%Y-%m-%d %H-%M-%S')
    print(info1) # 2020-04-30 20-00-00
    print(info2) # 2020-06-24 20-00-00
    print(info3) # 2020-05-20 00-00-00
    
    # ##### 时间戳和datetime关系 #####
    import time
    v1=time.time()
    print(v1) # 打印当前时间戳
    v2=datetime.fromtimestamp(v1) # 将此时间戳转换为datetime格式时间
    print(v2)
    
    v3=datetime.now() # 获取当前datetime格式时间
    v4=v3.timestamp() # 将此时间转换为时间戳
    print(v4)

    2.13 异常处理

    try:
        val = input('请输入数字:')
        num = int(val)
    except Exception as e:
        print('操作异常')
    # import requests
    #
    # try:
    #     ret = requests.get('http://www.google.com')
    #     print(ret.text)
    # except Exception as e:
    #     print('请求异常')
    def func(a):
        try:
            return a.strip()
        except Exception as e:
            pass
        return False
    
    v = func('alex')
    if not v:
        print('函数执行失败')
    else:
        print('结果是',v)
    # 练习
    # 1. 写函数,函数接受一个列表,请将列表中的元素每个都 +100
    def func(arg):
       result = []
       for item in arg:
           if item.isdecimal():
               result.append(int(item) + 100)
    return result

    # 2. 写函数去,接受一个列表。列表中都是url,请访问每个地址并获取结果。
    import requests
    def func(url_list):
       result = []
       try:
           for url in url_list:
               response = requests.get(url)
               result.append(response.text)
    except Exception as e:
           pass
    return result
    # 此循环会在遇到google时终止,并不会循环bing

    def func2(url_list):
       result = []
       for url in url_list:
           try:
               response = requests.get(url)
               result.append(response.text)
           except Exception as e:
               pass
    return result
    # 此循环会遍历完列表中所有元素

    func(['http://www.baidu.com','http://www.google.com','http://www.bing.com'])
  • 相关阅读:
    fn project 试用之后的几个问题的解答
    fn project 扩展
    fn project 生产环境使用
    fn project 对象模型
    fn project AWS Lambda 格式 functions
    fn project 打包Function
    fn project Function files 说明
    fn project hot functions 说明
    fn project k8s 集成
    fn project 私有镜像发布
  • 原文地址:https://www.cnblogs.com/usherwang/p/12878006.html
Copyright © 2020-2023  润新知