zoukankan      html  css  js  c++  java
  • 常用模块

    一、时间模块

    1.1、time模块分为三种格式

    1.1.1、时间戳    time.time

      从1970年到现在的秒数

      作用:用于时间间隔的计算

    print(time.time())

    1.1.2、格式化时间    time.strftime

      按照某种格式显示的时间:2020-3-30  11:22:33

      作用:用于展示时间

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

    1.1.3、结构化时间     local.time

      展示当前时间的某一部分

      作用:用于单独获取时间的一部分

    res=time.localtime()
    print(res)
    print(res.tm_year)
    print(res.tm_yday)

    1.2、datetime模块

      datetime模块用于计算当前时间到一定时间后的计算

    print(datetime.datetime.now())
    print(datetime.datetime.now() + datetime.timedelta(days=3))
    print(datetime.datetime.now() + datetime.timedelta(weeks=1))

    1.3、时间模块的使用

      人类能够识别的只有格式化时间,因此格式化时间也是两种时间格式装换的中间站

    1.3.1、时间格式间的转换

      时间戳转换成结构化时间

    tp_time=time.time()
    print(time.localtime(tp_time))

      结构化时间转换成时间戳

    import time
    # s_time=time.localtime()
    # print(time.mktime(s_time))

      格式化时间转换成结构化时间

    print(time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S'))
    ##time.struct_time(tm_year=1988, tm_mon=3, tm_mday=3, tm_hour=11, tm_min=11, tm_sec=11, tm_wday=3, tm_yday=63, tm_isdst=-1)

      结构化时间转换成格式化时间

    s_time=time.localtime()     #赋值现在的时间
    print(time.strftime('%Y-%m-%d %H:%M:%S',s_time)) 

    1.3.2、时间模块的综合使用

      格式化时间   转换成   结构化时间   再转换成   时间戳

    struct_time=time.strptime('1988-03-03 11:11:11','%Y-%m-%d %H:%M:%S')       #在已知的时间上进行更改,转换成结构化时间
    timestamp=time.mktime(struct_time)+7*86400
    print(timestamp)     #结构化时间转换成时间戳

      时间戳转换成结构化时间再转换成格式化时间

    res=time.strftime('%Y-%m-%d %X',time.localtime(timestamp))
    print(res)

    1.3.3、time模块:本地时间与世界时间 (了解)

    print(time.localtime())
    print(time.gmtime()) # 世界标准时间,了解
    print(time.localtime(333333333))
    print(time.gmtime(333333333))

    1.3.4、datetime:本地时间与世界时间(了解)

    print(datetime.datetime.now())    #现在的本地时间
    print(datetime.datetime.utcnow())   #现在的世界时间
    print(datetime.datetime.fromtimestamp(333333))    #1970年333333秒的本地时间

    二、随机模块

    2.1、random 的使用

    import random
    
    print(random.random()) #(0,1)----float    大于0且小于1之间的小数
    print(random.randint(1, 3))  # [1,3]    大于等于1且小于等于3之间的整数
    
    print(random.randrange(1, 3))  # [1,3)    大于等于1且小于3之间的整数
    
    print(random.choice([111, 'aaa', [4, 5]]))  # 1或者23或者[4,5]
    
    print(random.sample([111, 'aaa', 'ccc','ddd'],2))  # 列表元素任意2个组合
    
    print(random.uniform(1, 3))  # 大于1小于3的小数,如1.927109612082716
    
    item = [1, 3, 5, 7, 9]
    random.shuffle(item)  # 打乱item的顺序,相当于"洗牌"
    print(item)

    2.2、random模块的应用

      随机验证码:随机从大小写字母以及数字中取出一个数字

    def func(n=4):
        res=''
        for line in range(n):
            s1=chr(random.randint(65,90))
            s2=chr(random.randint(97,122))
            s3=str(random.randint(0,9))
            res+=random.choice([s1,s2,s3])
        return res
    print(func())

    三、os模块

    3.1、os模块的作用:获取文件夹下所有子文件以及子文件夹的名字

    import os

    res=os.listdir('.')
    print(res)
    size=os.path.getsize(r'/Users/linhaifeng/PycharmProjects/s14/day22/01 时间模块.py')
    print(size)

    3.2、os.remove()  删除文件

    os.rename("oldname","newname")  重命名文件/目录

    3.3、os.system()执行命令,并显示

    os.system("bash command")  运行shell命令,直接显示

    3.4、os.environ()   获取环境变量

    规定:key与value必须都为字符串
    os.environ['aaaaaaaaaa']='111'    #添加到环境变量中
    print(os.environ)

    3.5、os.path.dirname     返回文件的文件夹路径

    # 返回path的目录。其实就是os.path.split(path)的第一个元素
    print(os.path.dirname(r'/a/b/c/d.txt'))      #/a/b/c

    3.6、os.path.basename    分隔文件夹以及文件

    print(os.path.basename(r'/a/b/c/d.txt'))
    #/a/b/c
        d.txt

    3.7、os.path.isfile ()  判断文件是否存在

    print(os.path.isfile(r'笔记.txt'))   #判断文件是否存在,输出True or False

    3.8、os.path.isdir()    判断文件夹是否存在   

    # 如果path是一个存在的目录,则返回True。否则返回False
    print(os.path.isdir(r'aaa'))

    3.9、os.path.join()   将路径组合,忽略第一个参数

    # 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    print(os.path.join('a','/','b','c','d'))

    3.10、返回路径的选择

      推荐使用

    BASE_DIR=os.path.dirname(os.path.dirname(__file__))
    print(BASE_DIR)

      不推荐使用

    BASE_DIR=os.path.normpath(os.path.join(
        __file__,
        '..',
        '..'
    ))
    print(BASE_DIR)

      新功能

     #在python3.5之后,推出了一个新的模块pathlib
    from pathlib import Path
    
    res = Path(__file__).parent.parent  #返回当前文件上一级的上一级
    print(res)
    
    
    res=Path('/a/b/c') / 'd/e.txt'  #   路径合并   acde.txt
    print(res)
    
    print(res.resolve())    # 是路径的/变成       C:acde.txt

    四、sys模块

    4.1、

    sys.argv()          命令行参数List,第一个元素是程序本身路径

    4.2、sys.argv  的使用  :copy脚本

    import sys

    src_file=input('源文件路径: ').strip() dst_file=input('目标文件路径: ').strip() src_file=sys.argv[1] dst_file=sys.argv[2] # 判断 with open(r'%s' %src_file,mode='rb') as read_f, open(r'%s' %dst_file,mode='wb') as write_f: for line in read_f: write_f.write(line)

    4.3、打印进度条

    import time
    
    
    def progress(percent):
        if percent > 1:
            percent = 1
        res = int(50 * percent) * '#'
        print('
    [%-50s] %d%%' % (res, int(100 * percent)), end='')
    
    recv_size=0
    total_size=1025011
    
    while recv_size < total_size:
        time.sleep(0.01) # 下载了1024个字节的数据
    
        recv_size+=1024 # recv_size=2048
    
        # 打印进度条
        # print(recv_size)
        percent = recv_size / total_size  # 1024 / 333333
        progress(percent)
  • 相关阅读:
    第四次作业
    angular2 安装 打包成发布项目过程
    关于cannot find module 'xxxx’的一个可能解决方法。
    对cordova插件配置文件plugin.xml的理解
    如何找某个样式属于哪个Element
    如何用plugman编辑和添加cordova插件
    python命令行使用的问题
    如何使用Sencha touch 构建基于Cordova的安卓项目
    tensorflow1.0.0 弃用了几个operator写法
    Asp.net(C#)给图片加上水印效果和按比例生成高质量缩略图
  • 原文地址:https://www.cnblogs.com/jingpeng/p/12602080.html
Copyright © 2011-2022 走看看