常用模块

OS模块

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
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下为"\t\n",Linux下为"\n"
os.pathsep    输出用于分割文件路径的字符串
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所指向的文件或者目录的最后修改时间

sys模块

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

sys.exit(n)        退出程序,正常退出时exit(0)
sys.version        获取Python解释程序的版本信息
sys.maxint         最大的Int
sys.path           返回模块的搜索路径,初始化时使用PYTHONPATH环境变量的值
sys.platform       返回操作系统平台名称
sys.stdout.write('please:')
val = sys.stdin.readline()[:-1]

hashlib模块

import hashlib                        
s = hashlib.sha256()    #sha256算法,还有md
s.update('hello world'.encode('utf8'))
print(s.hexdigest())  #s的密文用16进制打印出来  

logging模块

很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug()info()warning()error() and critical() 5个级别,下面我们看一下怎么用。

import logging  
logging.basicConfig(level=logging.DEBUG,  
                    format='%(asctime)s %(filename)s[line:%(lineno)d] %(levelname)s %(message)s',  
                    datefmt='%a, %d %b %Y %H:%M:%S',  
                    filename='/tmp/test.log',  
                    filemode='w')  
  
logging.debug('debug message')  
logging.info('info message')  
logging.warning('warning message')  
logging.error('error message')  
logging.critical('critical message')

 另外还有一个模块级别的函数是logging.getLogger([name])

import logging

logger = logging.getLogger()  #创建一个logger对象

fh = logging.FileHandler('test.log') #创建一个文件handler,用于写入日志文件
ch = logging.StreamHandler() #再创建一个handler, 用于输出到控制台、屏幕
#格式器
formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s')

fh.setFormatter(formatter)
ch.setFormatter(formatter)

logger.addHandler(fh)  #logger对象添加多个fh和ch对象
logger.addHandler(ch)

logger.setLevel(logging.DEBUG)#设置logger级别
#logger = logging.Logger('useer_logger',level = logging.INFO) #另一种方式
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')

一个应用:

import os
import time
import logging
from config import settings


def get_logger(card_num, struct_time):

    if struct_time.tm_mday < 23:
        file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon, 22)
    else:
        file_name = "%s_%s_%d" %(struct_time.tm_year, struct_time.tm_mon+1, 22)

    file_handler = logging.FileHandler(
        os.path.join(settings.USER_DIR_FOLDER, card_num, 'record', file_name),
        encoding='utf-8'
    )
    fmt = logging.Formatter(fmt="%(asctime)s :  %(message)s")
    file_handler.setFormatter(fmt)

    logger1 = logging.Logger('user_logger', level=logging.INFO)
    logger1.addHandler(file_handler)
    return logger1

configparser模块(配置文件)

创建:

import configparser  #配置文件模块

config = configparser.ConfigParser()
config["DEFAULT"] = {'ServerAliveInterval': '45',
                     'Compression': 'yes',
                     'CompressionLevel': '9'}

config['bitbucket.org'] = {}
config['bitbucket.org']['User'] = 'hg'
config['topsecret.server.com'] = {}
topsecret = config['topsecret.server.com']
topsecret['Host Port'] = '50022'  # mutates the parser
topsecret['ForwardX11'] = 'no'  # same here
config['DEFAULT']['ForwardX11'] = 'yes'
with open('example.ini', 'w') as configfile:
    config.write(configfile)

结果:

[DEFAULT]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
forwardx11 = yes

[bitbucket.org]
user = hg

[topsecret.server.com]
host port = 50022
forwardx11 = no

读取:

import configparser  #配置文件模块

config = configparser.ConfigParser()

config.read('example.ini') #读出文件内容 print(config.sections()) #打印出除了DEFAULT之外的其他section print(config.defaults()) #读出DEFAULT print(config['bitbucket.org']['User']) #查看某一项 #hg for key in config: print(key) '''DEFAULT bitbucket.org topsecret.server.com''' for key in config['bitbucket.org']: #查看某一个模块的所有内容,会把默认的也取出来 print(key) ''' user serveraliveinterval compression compressionlevel forwardx11 '''

删除:

import configparser  #配置文件模块

config = configparser.ConfigParser()

config.remove_section('topsecret.server.com')  #删除topsecret.server.com模块

config.set('bitbucket.org', 'User', 'alex')  #将bitbucket.org下的User的值改为alex,没有的话是增加

config.remove_option('bitbucket.org', 'User')  #删除bitbucket.org下的User

config.write(open('example.ini', 'w'))    #必须加这么一条,实际上是新建新文件并覆盖原文件

 

re模块(正则)

作用:匹配字符串

字符串给的方法是完全匹配,正则可以模糊匹配

方法:findall()    找到所有匹配项,以列表输出

           search()     只找到第一个匹配到的项,返回对象,如果想取出内容,用.group()

           match()      只在字符串开始匹配

           split()         拆分,[j, s] , 先用j拆分,再用s将拆分完的进行拆分

           sub()         替换     如:re.sub('a..x','sopooob','hehisoialexki')

           compile()     编写规则   如: obj = re.compile('\.com)    obj.findall('sjigohoaho.comji) 

           subn()      替换后返回结果和替换的次数

           finditer()     找到匹配项后返回一个迭代对象

           

1 普通字符:大多数字符和字母都会和自身匹配
              >>> re.findall('alvin','yuanaleSxalexwupeiqi')
                      ['alvin'] 

2 元字符:      .    ^    $    *    +    ?    { }    []    |    ( )     \

元字符之. ^ $ * + ? { }

. 通配符   代指所有内容,除了换行符,但一个.只能代指一个字符

^ 尖角符   以后面的字符开头的字符串

$           只在结尾匹配

*          重复匹配      .* 指0到多个字符

+        重复匹配, 1到无穷个

?        重复匹配, 0或1 个

{}          重复匹配, {n} 指n个   {} 代表正无穷。{1,}相当于+, {0,1}相当于?

 []           字符集    例如 [c,d] 、[c,d,e]、  [a-z]、等   还有取消元字符的特殊功能,如[w, *],但是,三个字符除外:(\   ^ -)

 

^放在[] 里表示取反的意思,即”非“

\       斜杠    反斜杠后边跟元字符去除特殊功能,反斜杠后边跟普通字符实现特殊功能

         \d    匹配任何十进制数

         \D    匹配任何非数字字符

         \s       匹配任何空白字符

          \S     匹配任何非空白字符

           \w   匹配任何字母数字字符,

           \W   匹配任何非字母数字字符

           \b     匹配一个特殊边界,也就是指单词与空格等特殊字符间的位置

如果想要匹配字符串中的\,需要用\\\\,或者前边加r       ,如:

ret = re.findall('\\\\','sdfg\opa')
print(ret)            # ['\\']
ret1 = re.findall('\\bBlo', 'Blow')
print(ret1)         #['Blo']
ret = re.findall(r'\\','sdfg\opa')
print(ret)            #['\\']
ret1 = re.findall(r'\bBlo', 'Blow')
print(ret1)           #['Blo']

 

()   将多个字符组成一组

#    ?P<id> 是固定的命名格式
ret = re.search('(?P<id>\d{3})/(?P<name>\w{3})','weediajidg123/ooo') #其中“/”也可换成“,”
print(ret.group())
print(ret.group('id'))
print(ret.group('name'))

# 123/ooo
# 123
# ooo

 findall补充:

ret = re.findall('www.(\w+).com','www.baidu.com') #() 将匹配内容分组,匹配所有,但只取括号内内容
print(ret) #['baidu']
ret1 = re.findall('www.(?:\w+).com','www.baidu.com')# ?:表示取消特殊功能
print(ret1) #['www.baidu.com']
ret2 = re.findall('www.\w+.com','www.baidu.com')
print(ret2) #['www.baidu.com']

 

posted on 2018-04-25 17:43  11wayne  阅读(126)  评论(0编辑  收藏  举报

导航