zoukankan      html  css  js  c++  java
  • 15.常用模块【time/os/sys】

    初涉模块

    在python中,能开辟自己作用域的只有函数、类以及模块
    for循环if-else循环均不能实现开辟自己的作用域。

    >>> x = 3
    >>> for i in range(10):
    …     x = 55
    …
    …
    >>> print(x)
    55

    “模块就是.py文件”

    import xxxxx

    time

    • 时间戳:
    >>> time.time()
    1493168755.906269
    • 时间字符串
    >>> time.strftime('%Y-%m-%d %X')
    '2017-04-26 09:06:58'

    小写的y表示后两位的年份
    后面的M和m分别代表分钟数(minutes)和月份(month)

    Commonly used format codes:
    
        %Y  Year with century as a decimal number.
        %m  Month as a decimal number [01,12].
        %d  Day of the month as a decimal number [01,31].
        %H  Hour (24-hour clock) as a decimal number [00,23].
        %M  Minute as a decimal number [00,59].
        %S  Second as a decimal number [00,61].
        %z  Time zone offset from UTC.
        %a  Locale's abbreviated weekday name.
        %A  Locale's full weekday name.
        %b  Locale's abbreviated month name.
        %B  Locale's full month name.
        %c  Locale's appropriate date and time representation.
        %I  Hour (12-hour clock) as a decimal number [01,12].
        %p  Locale's equivalent of either AM or PM.
    
    • 结构化时间
    >>> time.localtime()
    time.struct_time(tm_year=2017, tm_mon=4, tm_mday=26, tm_hour=9, tm_min=15, tm_sec=13, tm_wday=2, tm_yday=116, tm_isdst=0)

    tm_isdst----夏令时

    >>> c = time.localtime()
    >>> c.tm_year
    2017

    结构化时间就是用来对时间进行操作的

    >>> help(time.localtime)
    Help on built-in function localtime in module time:
    
    localtime(…)
        localtime([seconds]) -> (tm_year,tm_mon,tm_mday,tm_hour,tm_min,
                                  tm_sec,tm_wday,tm_yday,tm_isdst)
    
        Convert seconds since the Epoch to a time tuple expressing local time.
        When 'seconds' is not passed in, convert the current time instead.
    

    时间形式的转换

    时间戳
    ||

    mktime/
    >>> time.mktime(time.localtime())
    1493170076.0

    ||

    格式化时间
    strftime/strptime

    >>> time.strftime('%Y-%m-%d %X',time.localtime(time.time()-24*3600))
    '2017-04-25 09:33:00'

    ||

    time.ctime()
    time.asctime()

    随机数模块random

    random.random()
    默认0-1取浮点数
    规定范围取浮点数

    >>> random.uniform(1,3)
    2.969686720232199

    范围取整

    >>> random.randint(1,9)
    5
    >>> random.randint(1,9)
    4
    >>> random.randint(1,9)
    1
    >>> random.randrange(1,9)
    6
    >>>
    >>> random.randrange(1,9)
    2

    规定范围取值

    >>> random.choice(['a','b','c','d'])
    'c'
    >>> random.choice(['a','b','c','d'])
    'c'
    >>> random.choice(['a','b','c','d'])
    'a'
    >>> random.choice(['a','b','c','d'])
    'b'
    >>> random.choice(['a','b','c','d'])
    'a'

    规定范围取多个值

    >>> random.sample(['a','b','c','d'],2)
    ['a', 'c']

    随机排序

    >>> item = [1,2,4,5,9,6,3]
    >>> random.shuffle(item)
    >>> item
    [4, 6, 5, 1, 2, 3, 9]

    应用实例:生成五位验证码

    import random
    def validate():
        l=[chr(i) for i in range(97,123)]
        l.extend([1,22])
        # .extend方法就是一个操作,没有返回值
        item  =random.sample(l,5)
        sumstr = ''
        for i in item:
            sumstr += i
        print(sumstr)
    
    validate()

    hashlib

    摘要算法

    计算一个字符串的md5值

    >>> import hashlib
    >>> m = hashlib.md5()
    >>> m.update('scott')
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    TypeError: Unicode-objects must be encoded before hashing
    >>> m.update(b'scott')
    >>> print(m.hexdigest())
    21f63c6e971cd913a9c147e8652ca659
    import hashlib
    m= hashlib.md5()
    m.update('alex'.encode('utf8'))
    
    print(m.hashdigest())

    os模块

    import os

    # 当前工作目录
    >>> os.getcwd()
    'D:\Users\sss'
    
    # 修改当前工作目录
    >>> os.chdir('I:')
    >>> os.getcwd()
    'I:\'
    
    # 创建文件
    >>> os.makedirs('aaa/bbb')
    # 删除文件
    >>> os.removedirs('aaa/bbb')
    # 如果文件不为空,则无法删除
    >>> os.rmdir('aaa/bbb')
    
    # 查看当前的文件夹内容
    >>> os.listdir()
    ['$RECYCLE.BIN', 'cn_windows_10_enterprise_x64_dvd_6846957', 'System Volume Information', '~putfile0.im_', '游戏']
    
    # 查看文件状态
    >>> os.stat('游戏')
    os.stat_result(st_mode=16895, st_ino=13510798882112605, st_dev=1009602189, st_nlink=1, st_uid=0, st_gid=0, st_size=98304, st_atime=1493138044, st_mtime=1493138044, st_ctime=1492582673)

    os.system

    os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
    os.chdir("dirname")  改变当前脚本工作目录;相当于shell下cd
    os.curdir  返回当前目录: ('.')
    os.pardir  获取当前目录的父目录字符串名:('..')
    os.makedirs('dirname1/dirname2')    可生成多层递归目录
    os.removedirs('dirname1')    若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
    os.mkdir('dirname')    生成单级目录;相当于shell中mkdir dirname
    os.rmdir('dirname')    删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
    os.listdir('dirname')    列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
    os.remove()  删除一个文件
    os.rename("oldname","newname")  重命名文件/目录
    os.stat('path/filename')  获取文件/目录信息
    os.sep    输出操作系统特定的路径分隔符,win下为"\",Linux下为"/"
    os.linesep    输出当前平台使用的行终止符,win下为"	
    ",Linux下为"
    "
    os.pathsep    输出用于分割文件路径的字符串 win下为;,Linux下为:
    os.name    输出字符串指示当前使用平台。win->'nt'; Linux->'posix'
    os.system("bash command")  运行shell命令,直接显示
    os.environ  获取系统环境变量
    os.path.abspath(path)  返回path规范化的绝对路径
    os.path.split(path)  将path分割成目录和文件名二元组返回
    os.path.dirname(path)  返回path的目录。其实就是os.path.split(path)的第一个元素
    os.path.basename(path)  返回path最后的文件名。如何path以/或结尾,那么就会返回空值。即os.path.split(path)的第二个元素
    os.path.exists(path)  如果path存在,返回True;如果path不存在,返回False
    os.path.isabs(path)  如果path是绝对路径,返回True
    os.path.isfile(path)  如果path是一个存在的文件,返回True。否则返回False
    os.path.isdir(path)  如果path是一个存在的目录,则返回True。否则返回False
    os.path.join(path1[, path2[, …]])  将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
    os.path.getatime(path)  返回path所指向的文件或者目录的最后存取时间
    os.path.getmtime(path)  返回path所指向的文件或者目录的最后修改时间
    os.path.getsize(path) 返回path的大小
    
    >>> os.system('dir')
     驱动器 I 中的卷没有标签。
     卷的序列号是 3C2D-4E8D
    
     I: 的目录
    
    2017/03/25  23:54    <DIR>          cn_windows_10_enterprise_x64_dvd_6846957
    2017/03/26  00:43       185,526,784 ~putfile0.im_
    2017/04/26  00:34    <DIR>          游戏
                   1 个文件    185,526,784 字节
                   2 个目录 29,074,653,184 可用字节
    0
    
    #获取绝对路径
    >>> os.path.abspath('游戏')
    'I:\游戏'
    
    >>> b = os.path.basename('I:\游戏')
    >>> d = os.path.dirname('I:\游戏')
    >>> print(d,b)
    I: 游戏
    
    # 操作系统的特定分隔符
    >>> print(d+os.sep+b)
    I:\游戏
    
    # 正确的拼接路径方式
    >>> os.path.join(d,b)
    'I:\游戏'

    sys

    sys.argv 命令行参数List,第一个元素是程序本身路径
    sys.exit(n) 退出程序,正常退出时exit(0)
    sys.version 获取Python解释程序的版本信息
    sys.maxint 最大的Int值
    sys.path 返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
    sys.platform 返回操作系统平台名称

    >>> import sys
    >>> sys.version
    '3.6.1 (v3.6.1:69c0db5, Mar 21 2017, 18:41:36) [MSC v.1900 64 bit (AMD64)]'
    
    # sys.argv
    
    >>> sys.path
    ['', 'D:\Program Files\Python36\python36.zip', 'D:\Program Files\Python36\DLLs', 'D:\Program Files\Python36\lib', 'D:\Program Files\Python36', 'D:\Program Files\Python36\lib\site-packages']
    

    <wiz_tmp_tag id="wiz-table-range-border" contenteditable="false" style="display: none;">

  • 相关阅读:
    分布式训练基本原理
    服务化部署框架Paddle Serving
    Paddle Inference原生推理库
    源码编译优化
    推理部署概述
    深度学习模型组网
    在这里
    什么是响应式编程,为什么使用它?
    时间管理:如何充分利用你的24小时-吉姆·兰德尔.pdf
    Win10激活工具
  • 原文地址:https://www.cnblogs.com/scott-lv/p/7469157.html
Copyright © 2011-2022 走看看