Python学习 DAY 18 os模块,sys模块,hashlib模块,logging模块,正则表达式
***********************************os模块********************************************
os.getcwd() 文件所处的路径
os.chdir(‘r/c:user’) 改变工作目录
os.curdir 返回当前路径
os.pardir 返回两层目录
os.mkdir('xxx') 生成一个文件夹
os.makedirs('abc\\alex') 生成一个两层文件夹,在当前路径下
os.rmdir()删除一个空文件夹
os.removedirs('abc\\alex\\alvin') 先判断是否为空文件夹,空文件夹则删掉;如果有内容,则不删
os.listdir() 列出当前路径所有文件夹,放在一个列表里
os.remove() 删除文件,不能删文件夹
os.rename("oldname","newname") 文件改名字
os.stat('xxx') 获取文件信息,可获取文件大小,时间
os.sep 获取当前系统的路径分隔符,win\\,Linux/
os.linesep 获取当前系统的换行分隔符 window:\r\n;Linux:\n;mac:\r
os.pathsep 当前平台分割文件路径字符串
os.system 执行shell命令,即cmd-python
os.environ 环境变量
os.path.abspath() 拿相对路径的绝对路径
os.path.split() 将文件名和路径分割
os.path.dirname(‘路径’) 取出文件所在的文件夹的绝对路径
os.path.basename(path) 取出path最后的文件名
os.path.exists(path) 判断是否存在当前路径,存在返回TRUE
os.path.isabs(path) 判断是否为绝对路径,是为true
os.path.isfile(path) 判断path是否为存在的文件,是为true
os.path.isdir(path) 判断path是否为存在的目录,是为true
os.path.join.([a,b]) 路径拼接*******************
os.path.getatime(path) path指向文件的存取时间
os.path.getmtime(path) path指向文件的修改时间
***********************************sys模块(与python解释器进行交互)************************
sys.argv 命令行参数list,第一个元素是程序本身路径
sys.exit(n) 退出程序,正常退出时exit(0)
sys.path 搜寻模块路径的列表
sys.platform 显示当前平台
***********************************hashlib模块(加密)***********************
1.md5算法
m=hashlib.md5 拿到md5对象
m.update('hello world'.encode('utf8'))
m.hexdigest() ======一堆十六进制密文
2.sha算法
s=hashlib.sha256()
s.update('hello world')
s.hexdigest() =========密文
***********************************logging模块(日志)***********************
五种日志级别
logging.debug('debug message') 默认不打印 logging.info('info message') 默认不打印 logging.warning('warning message'(可按需求修改)) logging.error('error message') logging.critical('critical message')
基本的日志配置:
logging basicconfig(level=xxxxxxxx(级别,logging.DEBUG),
format=%(asctime)s %(filename)s %s[line:%lineno)d] %(levelname)s %(message)
datefmt='%Y %H' 时间格式
filename='/tmp/test.log' 文件名及位置 ,不写这行则在屏幕输出
filemode='a' 写入文件模式,不删除旧的
filename 带着路径的文件名
filemode 文件打开方式,默认为a
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用户输出的消息
屏幕和文件同时输出的方式:***
import logging logger = logging.getLogger() 创建一个logger对象
# 创建一个handler,用于写入日志文件 fh = logging.FileHandler('test.log') # 再创建一个handler,用于输出到控制台 ch = logging.StreamHandler() 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.debug('logger debug message') logger.info('logger info message') logger.warning('logger warning message') logger.error('logger error message') logger.critical('logger critical message')
***********************************configParser模块(配置文件)***********************importconfigparser
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 parsertopsecret['ForwardX11'] = 'no' # same hereconfig['DEFAULT']['ForwardX11'] = 'yes'<br>with open('example.ini', 'w') as configfile: config.write(configfile)import configparser
config = configparser.ConfigParser()
#---------------------------------------------查
print(config.sections()) #[]
config.read('example.ini')
print(config.sections()) #['bitbucket.org', 'topsecret.server.com'] 取块
print('bytebong.com' in config)# False
print(config['bitbucket.org']['User']) # hg 取块下面的值
print(config['DEFAULT']['Compression']) #yes
print(config['topsecret.server.com']['ForwardX11']) #no
for key in config['bitbucket.org']:
print(key) 打印default和bitbucket.org中地所有键,default一直跟着
# user
# serveraliveinterval
# compression
# compressionlevel
# forwardx11
print(config.options('bitbucket.org'))#['user', 'serveraliveinterval', 'compression', 'compressionlevel', 'forwardx11']
print(config.items('bitbucket.org')) #[('serveraliveinterval', '45'), ('compression', 'yes'), ('compressionlevel', '9'), ('forwardx11', 'yes'), ('user', 'hg')]
print(config.get('bitbucket.org','compression'))#yes
#---------------------------------------------删,改,增(config.write(open('i.cfg', "w")))
config.add_section('yuan')
config.remove_section('topsecret.server.com')
config.has_section('topsecret.server.com') false 是否有字符串
config.remove_option('bitbucket.org','user')
config.set('bitbucket.org','k1','11111') 找到bitbucket.org下的k1键,修改为11111
config.write(open('i.cfg', "w")) 必须重新生成一个文件,文件内容不能被修改,只能被覆盖
增删改查

浙公网安备 33010602011771号