• 模块


    一.os

    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的大小
    

    二.logging模块

    import logging
    
    logging.basicConfig(level=logging.DEBUG,
                        format='%(asctime)s %(lineno)d %(levelname)s %(message)s',
                        datefmt='%Y-%m-%d %X',
                        filename='log.txt',
                        filemode='w')
    
    
    logging.debug('debug message')
    logging.info('info message')
    logging.warning('warning message')
    logging.error('error message')
    logging.critical('critical message')
    
    logging.basicConfig()函数中可通过具体参数来更改logging模块默认行为,可用参数有:
    
    filename:用指定的文件名创建FiledHandler,这样日志会被存储在指定的文件中。
    filemode:文件打开方式,在指定了filename时使用这个参数,默认值为“a”还可指定为“w”。
    format:指定handler使用的日志显示格式。
    datefmt:指定日期时间格式。
    level:设置rootlogger(后边会讲解具体概念)的日志级别
    stream:用指定的stream创建StreamHandler。可以指定输出到sys.stderr,sys.stdout或者文件(f=open(‘test.log’,’w’)),默认为sys.stderr。若同时列出了filename和stream两个参数,则stream参数会被忽略。
    
    format参数中可能用到的格式化串:
    %(name)s Logger的名字
    %(levelno)s 数字形式的日志级别
    %(levelname)s 文本形式的日志级别
    %(pathname)s 调用日志输出函数的模块的完整路径名,可能没有
    %(filename)s 调用日志输出函数的模块的文件名
    %(module)s 调用日志输出函数的模块名
    %(funcName)s 调用日志输出函数的函数名
    %(lineno)d 调用日志输出函数的语句所在的代码行
    %(created)f 当前时间,用UNIX标准的表示时间的浮 点数表示
    %(relativeCreated)d 输出日志信息时的,自Logger创建以 来的毫秒数
    %(asctime)s 字符串形式的当前时间。默认格式是 “2003-07-08 16:49:45,896”。逗号后面的是毫秒
    %(thread)d 线程ID。可能没有
    %(threadName)s 线程名。可能没有
    %(process)d 进程ID。可能没有
    %(message)s用户输出的消息
    配置参数

    logger对象配置

    def logger():
        logger = logging.getLogger()
        # 创建一个handler,用于写入日志文件
        fh = logging.FileHandler('test.log')
    
        # 再创建一个handler,用于输出到控制台
        ch = logging.StreamHandler()
    
        formatter = logging.Formatter('%(asctime)s %(lineno)d %(levelname)s %(message)s')
    
        fh.setFormatter(formatter)
        ch.setFormatter(formatter)
    
        logger.addHandler(fh) #logger对象可以添加多个fh和ch对象
        logger.addHandler(ch)
        return logger
    
    logger=logger()
    
    logger.debug('logger debug message')
    logger.info('logger info message')
    logger.warning('logger warning message')
    logger.error('logger error message')
    logger.critical('logger critical message')

    三. re

    #字符匹配(普通字符,元字符)
    #普通字符
    #元字符 . ^ $ * ? + {} [] | () : 反斜杠后边跟元字符去除特殊功能 反斜杠后边跟普通字符实现特殊功能 引用序号对应的字组所匹配的字符串 d 匹配任何十进制数,[0-9] D 匹配任何非数字字符,[^0-9] s 匹配任何空白字符,[ fv] S 匹配任何非空白字符,[ ^ fv] w 匹配任何数字字母字符,[a-zA-Z0-9_] W 匹配任何非字母数字字符,[^a-zA-Z0-9_]  匹配一个单词边界,也就是指单词和空格间的位置
     1 origin = "hello world hi"
     2 
     3 r = re.match("hw+",origin)
     4 print(r.group())           #获取匹配到的所有结果
     5     hello
     6     
     7 r = re.match("(h)(w+)",origin)
     8 print(r.groups())          #获取模型中匹配到的分组结果
     9     ('h', 'ello')
    10     
    11 r = re.match("(?P<n1>h)(?P<n2>w+)",origin)
    12     {'n1': 'h', 'n2': 'ello'}
    re.match #从头匹配
    origin = "hello alex alex bcd abcd lge acd 19"
    
    r = re.finditer("(a)((w+)(e))(?P<n1>x)",origin)
    for i in r:
        print(i)
            <_sre.SRE_Match object; span=(6, 10), match='alex'>
        print(i.group())
            alex
        print(i.groupdict())
            {'n1': 'x'}
    re.finditer
    import re
    
    origin = "hello alex hello alex bcd abcd lge acd 19"
    
    
    # .
    
    print(re.findall("h...o",origin))
        ['hello', 'hello']
    
    
    # ^
    
    print(re.findall("^h...o",origin))
        ['hello']
    
    # $
    
    print(re.findall("h...o$",origin))
        []
    
    # ?
    
    print(re.findall("d?","aaaddddccc"))
        ['', '', '', 'd', 'd', 'd', 'd', '', '', '', '']
    
    # +
    
    print(re.findall("d+","aaaddddccc"))
        ['dddd']
    
    # *
    
    print(re.findall("d*","aaaddddccc"))
        ['', '', '', 'dddd', '', '', '', '']
    
    # {}
    
    print(re.findall("d{4}","aaaddddccc"))
        ['dddd']
    
    #注意:前面的*,+,?等都是贪婪匹配,也就是尽可能匹配,后面加?号使其变成惰性匹配
    print(re.findall("ad*?","addddccc"))
        ['a']
    
    print(re.findall("ad*?","aaaaddddccc"))
        ['a', 'a', 'a', 'a']
    
    
    # []    []里面只有 ^ -  有特殊含义
    
    
    print(re.findall("a[bc]d","abdfffacd"))
        ['abd', 'acd']
    
    print(re.findall("q[a-z]","qab"))
        ['qa']
    
    print(re.findall("q[^a-z]*","q12355"))
        ['q12355']
    
    
    #匹配括号中没有括号
    print(re.findall("([^()]*)","12+(34*6+2-5*(2-1))"))
        ['(2-1)']
    re.findall #将匹配到的内容放到一个列表里
    # search ()
    
    print(re.search("(?P<name>[a-z]+)","alex36wusir34egon33").group())
        alex
    
    print(re.search("(?P<name>[a-z]+)d+","alex36wusir34egon33").group())
        alex36
    
    print(re.search("(?P<name>[a-z]+)d+","alex36wusir34egon33").group("name"))
        alex
    
    print(re.search("(?P<name>[a-z]+)(?P<age>d+)","alex36wusir34egon33").group("age"))
        36
    re.search
    #split 切割
    
    print(re.split(" ","alex egon hao"))
        ['alex', 'egon', 'hao']
    
    print(re.split("[ |]","alex egon|hao"))
        ['alex', 'egon', 'hao']
    
    print(re.split("[ab]","abc"))
        ['', '', 'c']
    
    print(re.split("[ab]","asdabcd"))
        ['', 'sd', '', 'cd']
    re.split 切割
    #sub 替换
    
    #将数字替换成A
    print(re.sub("d+","A","aakk123ddd55kk66"))
        aakkAdddAkkA
    
    #匹配前4次
    print(re.sub("d","A","aakk123ddd55kk66",4))
        aakkAAAdddA5kk66
    
    
    #subn 替换的次数按元组显示出来
    
    print(re.subn("d","A","aakk123ddd55kk66"))
        ('aakkAAAdddAAkkAA', 7)
    #sub 替换
    # () 优先显示括号中的内容
    
    print(re.findall("([^()]*)","12+(34*6+2-5*(2-1))"))
        ['(2-1)']
    
    print(re.findall("www.(baidu|163).com","www.baidu.com"))
        ['baidu']
    
    print(re.findall("www.(?:baidu|163).com","www.baidu.com"))
        ['www.baidu.com']
    
    print(re.findall("(abc)+","abcabcabc"))
    ['abc']
    
    print(re.findall("(?:abc)+","abcabcabc"))
        ['abcabcabc']
    () 优先显示括号中的内容

    四. time datetime

    #_*_coding:utf-8_*_
    __author__ = 'Alex Li'
    
    import time
    
    
    # print(time.clock()) #返回处理器时间,3.3开始已废弃 , 改成了time.process_time()测量处理器运算时间,不包括sleep时间,不稳定,mac上测不出来
    # print(time.altzone)  #返回与utc时间的时间差,以秒计算
    # print(time.asctime()) #返回时间格式"Fri Aug 19 11:14:16 2016",
    # print(time.localtime()) #返回本地时间 的struct time对象格式
    # print(time.gmtime(time.time()-800000)) #返回utc时间的struc时间对象格式
    
    # print(time.asctime(time.localtime())) #返回时间格式"Fri Aug 19 11:14:16 2016",
    #print(time.ctime()) #返回Fri Aug 19 12:38:29 2016 格式, 同上
    
    
    
    # 日期字符串 转成  时间戳
    # string_2_struct = time.strptime("2016/05/22","%Y/%m/%d") #将 日期字符串 转成 struct时间对象格式
    # print(string_2_struct)
    # #
    # struct_2_stamp = time.mktime(string_2_struct) #将struct时间对象转成时间戳
    # print(struct_2_stamp)
    
    
    
    #将时间戳转为字符串格式
    # print(time.gmtime(time.time()-86640)) #将utc时间戳转换成struct_time格式
    # print(time.strftime("%Y-%m-%d %H:%M:%S",time.gmtime()) ) #将utc struct_time格式转成指定的字符串格式
    
    
    
    
    
    #时间加减
    import datetime
    
    # print(datetime.datetime.now()) #返回 2016-08-19 12:47:03.941925
    #print(datetime.date.fromtimestamp(time.time()) )  # 时间戳直接转成日期格式 2016-08-19
    # print(datetime.datetime.now() )
    # print(datetime.datetime.now() + datetime.timedelta(3)) #当前时间+3天
    # print(datetime.datetime.now() + datetime.timedelta(-3)) #当前时间-3天
    # print(datetime.datetime.now() + datetime.timedelta(hours=3)) #当前时间+3小时
    # print(datetime.datetime.now() + datetime.timedelta(minutes=30)) #当前时间+30分
    
    
    #
    # c_time  = datetime.datetime.now()
    # print(c_time.replace(minute=3,hour=2)) #时间替换 

    今天项目遇到 2017-11-1   2017-11-30 我需要打印出他们之间的日期, 为了让我小弟武勇强也得到锻炼, 就让这傻逼5分钟给我做出来,没想到竟这傻逼用了一小时才把任务完成. 真他妈的丢人败兴....

    import time
    start_time = time.mktime(time.strptime("2017-11-01","%Y-%m-%d"))
    end_time = time.mktime(time.strptime("2017-12-01","%Y-%m-%d"))
    while start_time <= end_time:
        print(time.strftime("%Y-%m-%d",time.localtime(start_time)))
        start_time += 86400.0  

    第二天我又让这傻逼把每天的日期显示出来 代码如下

    import time
    start_time = time.mktime(time.strptime("2017-12-01","%Y-%m-%d"))
    end_time = time.mktime(time.strptime("2018-1-17","%Y-%m-%d"))
    w_dic = {"0":"星期日","1":"星期一","2":"星期二","3":"星期三","4":"星期四","5":"星期五","6":"星期六"}
    while start_time <= end_time:
        date_num_mode = time.strftime("%Y-%m-%d %w",time.localtime(start_time))
        date_ymd,date_w = date_num_mode.split(" ")
        print(date_ymd,w_dic[date_w])
        start_time += 86400.0
    

      

    海峰 

    苑昊 

    武沛齐

  • 相关阅读:
    软件架构阅读笔记04
    软件架构阅读笔记03
    TortoiseGit和intellij idea配置秘钥
    linux关闭在线登录用户
    汉化gitlab
    GitLab服务器搭建
    redis 中如何切换db
    弹性伸缩问题
    Filebeat+Logstash自定义多索引
    logstash
  • 原文地址:https://www.cnblogs.com/golangav/p/6187830.html
Copyright © 2020-2023  润新知