python之路(8)常用模块
目录
- os模块
- sys模块
- json模块
- pickle模块
- xml模块
- re模块
- logging模块
- configparser模块
- hashlib模块
- time模块
- random模块
- subprocess模块
os模块
- import os
- print(os.getcwd()) #获取当前文件的工作路径
- os.chdir('dirname') #切换当前的文件目录,相当于shell的cd os.chdir('.')
- os.makedirs('dirname1/dirname2') #递归新建文件夹
- os.mkdir('dirname') #生成文件夹
- os.removedirs('dirname1/dirname') #递归删除文件夹
- os.remove('dirname') #删除文件夹
- os.listdir('dirname') #查看文件目录,显示隐藏文件 ,相当于linux下的‘ls -a’
- os.rename('new_name') #重命名文件、目录
- os.stat('path/filename') #返回文件的大小,上一次修改,上一次访问时间等元数据
- os.sep #输出操作系统的路径分隔符 win下为"\\" linux下为"/"
- os.linesep #输出操作系统的行终止符 win下为"\r\n" linux下为"\n"
- os.pathsep #输出操作系统分割文件目录的字符 wim下为";" linux下为":"
- os.name #输出当前使用平台 win下为"nt" linux下为"posix"
- os.system("mkdir new_file") #运行shell命令,显示结果
- os.environ #获取系统变量
- os.path.abspath(path) #返回path规范化的绝对路径
- os.path.split(path) #将path分割成目录的文件,以一个元组返回
- os.path.dirname(path) #返回path的文件目录,相当于os.path.spile(path)的第一个元素
- os.path.basename(path) #返回path的文件名,相当于os.path.spile(path)的第二个元素
- os.path.exists(path) #判断文件路径是否存在,返回bool值
- os.path.isabs(path) #判断path是否是绝对路径
- os.path.isfile(path) #判断path是否是一个文件
- os.path.isdir(path) #判断path是是否是一个目录
- os.path.join(path1,path2) #将路径进行拼接,默认查找操作系统的符
- os.path.getatime(path) #返回path指向文件或目录的最后保存时间
- os.path.getmtime(path) #返回path所指向文件或目录的最后修改时间
sys模块
- import sys
- sys.exit() #退出程序,正常退出exit(0)
- sys.path #返回模块的搜索路径
- sys.version #返回python解释器的版本信息
- sys.platform #返回操作系统平台名称
- sys.stdout.write("") #将内容在终端显示 相当于print()
- sys.stdout.flush() #刷新终端缓存,即时显示终端内容
- sys.path.append(path) #追加模块搜索路径
json模块
- import json
- dic_test = {
- 'name':'chen',
- 'age': 21
- }
- data = json.dumps(dic_test) #将字典单引号都变成双引号的字符串,然后将字典转换成字符串--》<class 'str'>
- data = json.loads(data) #读取json内容,将字符串转换成字典格式--》<class 'dict'>
- json.dump(dic_test,文件句柄) #以json格式存到文件中
- data = json.load(文件句柄) #将文件内容已json格式读
pickle模块
- import pickle
- dic_test = {
- 'name':'chen',
- 'age': 21
- }
- data = pickle.dumps(dic_test) #序列化之后,将数据转换成字节--》<class 'bytes'>
- data = pickle.loads(data) #将序列化后的字节数据转换成字典格式--》<class 'dict'>
- pickle.dump(dic_test,文件句柄) #以字节数据存到文件中
- data = pickle.load(文件句柄) #读取数据字节从文件中读取,并转换成字典
xml模块
- <breakfast_menu>
- <food name="Belgian Waffles">
- <price>$6.95</price>
- <description>two of our famous Belgian Waffles with plenty of real maple syrup</description>
- <calories>650</calories>
- </food>
- <food name="Strawberry Belgian Waffles">
- <price>$8.95</price>
- <description>light Belgian waffles covered with strawberries and whipped cream</description>
- <calories>850</calories>
- </food>
- <food name="Berry-Berry Belgian Waffles">
- <price>$9.95</price>
- <description>light Belgian waffles covered with an assortment of fresh berries and whipped cream</description>
- <calories>900</calories>
- </food>
- </breakfast_menu>
xml_01
- import xml.etree.ElementTree as ET
- tree = ET.parse("xml_01")
- root = tree.getroot()
- for i in root: #遍历节点
- print(i.tag)
- print(i.attrib)
- for j in i:
- print(j.text)
- for price in root.iter('price'): #直接遍历price节点
- print(price.tag,price.text)
- for price in root.iter('price'): #修改
- new_price = '$'+str(float(price.text[1:]) + 1)
- price.text = new_price
- price.set('update','yes')
- for food in root.findall('food'): #删除
- if int(food.find('calories').text) == 900:
- root.remove(food)
- tree.write("xml_01") # 修改后,写入文件中
新建xml
- import xml.etree.ElementTree as ET
- breakfast_menu = ET.Element('breakfast_menu') #设置一个根节点,标签为breakfast_menu
- food = ET.SubElement(breakfast_menu,'food',attrib={'name':'Belgian Waffles'}) #在根节点food下建立子节点,添加属性
- food2 = ET.SubElement(breakfast_menu,'food',attrib={'name':'Strawberry Belgian Waffles'}) #在根节点food下建立子
- price = ET.SubElement(food,'price')
- price2 = ET.SubElement(food2,'price')
- price.text = '$15.98'
- price2.text = '$12.98'
- et = ET.ElementTree(breakfast_menu)
- et.write('new_text.xml',encoding='utf-8',xml_declaration=True)
- <?xml version='1.0' encoding='utf-8'?>
- <breakfast_menu>
- <food name="Belgian Waffles">
- <price>$15.98</price>
- </food>
- <food name="Strawberry Belgian Waffles">
- <price>$12.98</price>
- </food>
- </breakfast_menu>
new_text.xml
re模块
元字符 :. ^ $ * + ? { } [ ] | ( ) \
- import re
- #.^$
- re.findall('c..n', 'chencqwncaxn') #返回['chen', 'cqwn']
- re.findall('^c..n', 'chencqwncaxn') #“^”只匹配字符串开头,返回['chen']
- re.findall('c..n$', 'chencqwncaxn') #"$"匹配字符串结尾,返回['caxn']
- #*
- re.findall('x*', 'cxxxxxc') #‘*’匹配(0-∞)次,返回['', 'xxxxx', '', '']
- re.findall('cx*', 'cxxxxxc') #返回['cxxxxx', 'c']
- #+
- re.findall('x+', 'cxxxxxc') #+匹配(1-∞)次,返回['xxxxx']
- #{}
- re.findall('x{1,2}', 'cxwxxrxyxx') #“{1,2}”指定(1-2)次数,返回['x', 'xx', 'x', 'xx']
- re.findall('x{1,2}', 'cxxxxxc') #贪婪匹配,先取最多次 ,返回['xx', 'xx', 'x']
- #[]
- re.findall('c[xyz]', 'aazacxaaacyaa') #“[]”字符集,[]里是或的关系,返回['cx', 'cy']
- re.findall('c[a-z]', 'zacxaacyaacuaceaacn') #“[a-z]”匹配a到z的字符,返回['cx', 'cy', 'cu', 'ce', 'cn']
- re.findall('c[^a-z]', 'cqzxc2') #“[^a-z]”匹配除了a到z之外字符,返回['c2']
\d 匹配任何数字,相当于[0-9]
\D 匹配任何非数字字符,相当于[^0-9]
\s 匹配任何空白字符,相当于[\t\n\r\f\v]
\S 匹配任何非空白字符,相当于[^\t\n\r\f\v]
\w 匹配任何字母字符,相当于[0-9a-zA-Z_]
\W 匹配任何非字母字符,相当于[^0-9a-zA-Z_]
\b 匹配一个特殊字符边界,比如空格,&,#等
- #\
- re.findall('\d+', '13+(56*12/(12+3))') #匹配数字,返回['13', '56', '12', '12', '3']
- re.findall('\D+', '13+(56*12/(12+3))') #匹配非数字,返回['+(', '*', '/(', '+', '))']
- #|
- re.findall('ra|tb', 'raiiurtb') #“|”是或的关系,返回['ra', 'tb']
- #()
- re.findall('(abc)+', 'abcyyabc') #“()”分组匹配,返回['abc', 'abc']
- re.findall('www\.(baidu|163)\.com', 'asdwww.baidu.comqwe') #会优先返回分组匹配的内容,返回['baidu']
- print(re.findall('www\.(?:baidu|163)\.com', 'asdwww.baidu.comqwe')) #“?:”会取消输出优先级,输出完整内容,返回['www.baidu.com']
- #search
- re.search('\d+','aw34wer56') #只找到一个结果,并返回一个对象,group()方法查看value
- re.search('(?P<name>[a-z]+)(?P<age>\d+)', 'chen22liu23').group() #'?P<name>'指定分组名字,返回chen22
- re.search('(?P<name>[a-z]+)(?P<age>\d+)+', 'chen22liu23').group('name') #返回chen
- re.search('(?P<name>[a-z]+)(?P<age>\d+)+', 'chen22liu23').group('age') #返回22
- #match
- re.match('\d+','34asdfsdf').group() #相当于在re.search() 加一个“^”,返回34
- #split
- re.split(" ","I am chen") #按照规则分割,返回['I', 'am', 'chen']
- # 注:
- re.split("[a-z]", "7q4eyt45e9") #返回['7', '4', '', '', '45', '9']
- #sub()
- re.sub("\d", "chen", "ccc2aa434") #替换字符,返回cccchenaachenchenchen
- re.sub("\d", "chen", "ccc2aa434",2) #替换字符,并指定次数,返回cccchenaachen34
- re.subn("\d", "chen", "ccc2aa434") ##替换字符,并返回替换次数,返回('cccchenaachenchenchen', 4)
- #compile()
- com = re.compile('\d+') #保存匹配规则
- com.findall('asd23qweqwe455sdf') #返回['23', '455']
- #finditer()
- ret = re.finditer("\d+",'asd23qweqwe455sdf') #返回一个迭代器
- next(ret).group() #返回23
- re.findall('\([^()]*\)', "13+(56*12/(12+3))") #返回['(12+3)']
logging模块
- import logging
- logging.basicConfig(
- level=logging.DEBUG,#默认是warning级别
- filename='logger.log',#指定输出为文本,stream参数设置终端输出,两者选一
- filemode='w',#文本为写模式
- format='%(asctime)s %(filename)s [%(lineno)s] %(message)s'#指定输出格式
- )
- logging.debug('debug message')
- logging.info('info message')
- logging.warning('warning message')
- logging.error('error message')
- logging.critical('critical message')
- #返回:
- # 2018-10-30 08:32:48,238 logging_demo.py [15] debug message
- # 2018-10-30 08:32:48,238 logging_demo.py [16] info message
- # 2018-10-30 08:32:48,239 logging_demo.py [17] warning message
- # 2018-10-30 08:32:48,239 logging_demo.py [18] error message
- # 2018-10-30 08:32:48,239 logging_demo.py [19] critical message
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 字符串形式的当前时间。默认格式是“2018-10-30 2018-10-30 08:45:24,552 ” ,逗号后为毫秒
%(thread)d 线程ID,可能没有
%(threadName)s 线程名。可能没有
%(process)d 进程ID。可能没有
%(message)s 用户输出的消息
- import logging
- logger = logging.getLogger()#创建logger对象
- logger.setLevel("DEBUG")#定义输出级别
- fh = logging.FileHandler('logger.log')#定义文本输出handler
- sh = logging.StreamHandler()#定义终端输出handler
- fm = logging.Formatter('%(asctime)s %(module)s [%(lineno)s] %(message)s')#定义输出格式
- fh.setFormatter(fm)#绑定文本输出格式
- sh.setFormatter(fm)#绑定终端输出格式
- logger.addHandler(fh)#绑定文本输出
- logger.addHandler(sh)#绑定终端输出
- logger.debug('debug message')
- logger.info('info message')
- logger.warning('warning message')
- logger.error('error message')
- logger.critical('critical message')
- #终端和文本返回:
- # 2018-10-30 09:02:14,306 logging_demo [41] debug message
- # 2018-10-30 09:02:14,306 logging_demo [42] info message
- # 2018-10-30 09:02:14,307 logging_demo [43] warning message
- # 2018-10-30 09:02:14,307 logging_demo [44] error message
- # 2018-10-30 09:02:14,307 logging_demo [45] critical message
注:
- import logging
- logger1 = logging.getLogger('mylogger')
- logger1.setLevel("DEBUG")
- logger2 = logging.getLogger('mylogger')#与logger1为用一个mylogger对象
- logger2.setLevel("WARNING")#修改的是mylogger对象
configparser模块
- import configparser
- config = configparser.ConfigParser() #config={}
- config['DEFAULT'] = {
- 'Port' : '3000',
- 'Compression' : 'yes'
- }
- config['Path'] = {'1':'f:/aaa/1989works',
- '2':'f:/bbb/1990works',
- '3':'f:/ccc/1991works'
- }
- config['User'] = {'user': 'mike'}
- with open('example.ini','w') as f:
- config.write(f)
- [DEFAULT]
- port = 3000
- compression = yes
- [Path]
- 1 = f:/aaa/1989works
- 2 = f:/bbb/1990works
- 3 = f:/ccc/1991works
- [User]
- user = mike
example.ini
configparser对象
- import configparser
- #读
- config = configparser.ConfigParser()#创建configparser对象
- config.read('example.ini')#读取内容
- config.sections()#返回['Path', 'User']
- config['Path']['path_1'] #返回 f:/aaa/1989works
- for key in config['Path']:
- print(key)
- #返回
- # path_1
- # path_2
- # path_3
- # port
- # compression
- # 注: 默认返回DEFAULT下的内容
- config.options('Path') #以列表的形式,返回keys ['path_1', 'path_2', 'path_3', 'port', 'compression']
- config.items('Path') #返回键值对 [('port', '3000'), ('compression', 'yes'), ('path_1', 'f:/aaa/1989works'), ('path_2', ':/bbb/1990works'), ('path_3', 'f:/ccc/1991works')]
- config.get('Path', 'path_1') #得到value,返回f:/aaa/1989works
- config.write(open('i.cfg','w')) #写入到文件中
- #增,删,改
- config.add_section('Web') #添加Web块
- config.set('Web','url','www.baidu.com') #在Web块下添加键值对,‘url = www.baidu.com’
- config.remove_section('Web') #删除Web块
- config.remove_option('Web','url') #删除Web块下的url键值对
hashlib模块
加密相关操作,主要提供SHA1,SHA22,SHA256,SHA384,SHA512,MD5算法
- import hashlib
- obj = hashlib.md5()
- #obj = hashlib.md5('chen_rule'.encode('utf-8')) 防止明文太过简单
- obj.update('hello'.encode('utf-8'))
- obj.hexdigest() #返回5d41402abc4b2a76b9719d911017c592
- obj.update('root'.encode('utf-8'))
- obj.hexdigest() #是对‘helloroot’字符串的加密,返回88dc0a05547248a2a98e1660d67a5270
time模块
- import time
- time.time() #返回时间戳 1540867695.7234108秒
- time.localtime() #返回结构化当地时间
- #返回time.struct_time(tm_year=2018, tm_mon=10, tm_mday=30, tm_hour=10, tm_min=49, tm_sec=12, tm_wday=1, tm_yday=303, tm_isdst=0)
- time.localtime().tm_year #返回2018
- time.localtime(1540868162.4058135) #转换成结构化时间
- time.gmtime() #返回世界标准时间(UTC),与当地时间差8小时(东8区)
- #返回time.struct_time(tm_year=2018, tm_mon=10, tm_mday=30, tm_hour=2, tm_min=53, tm_sec=4, tm_wday=1, tm_yday=303, tm_isdst=0)
- #struct_time --> timestamp
- time.mktime(time.localtime()) #将结构化时间转换成时间戳,返回1540868265.0
- #struct_time --> strtime
- time.strftime('%Y-%m-%d %X', time.localtime()) #将结构化时间转换成strtime 返回2018-10-30 11:00:25
- #strtime --> timestamp
- time.strptime('2018:10:30:11:02:36', '%Y:%m:%d:%X') #将字符串时间转换成结构时间
- #返回time.struct_time(tm_year=2018, tm_mon=10, tm_mday=30, tm_hour=11, tm_min=2, tm_sec=36, tm_wday=1, tm_yday=303, tm_isdst=-1)
- time.asctime() #将结构化时间转换成字符串时间,不用手动定义字符串格式,返回Tue Oct 30 11:04:46 2018
- time.ctime() #将时间错转换成字符串时间,不用手动定义字符串格式,返回Tue Oct 30 11:04:46 2018
randorm模块
- import random
- random.random() #随机返回(0,1)之间的float类型的值
- random.randint(1,3) #随机返回[1,3]之间的int类型的数
- random.randrange(1,3) #随机返回[1,3)之间的int类型的数
- random.choice([11,22,33]) #随机返回列表中的一个值
- random.sample([11, 22, 33], 2) #随机返回列表中的两个值
- random.uniform(1,4) #返回指定返回的float类型的值
- item = [1, 2, 3, 4, 5]
- random.shuffle(item) #打乱列表的次序
- print(item)
subprocess模块
- import subprocess
- #两个进程间通信,用shell执行dir命令
- #标准输出、标准输入、标准错误都重定向到管道
- res = subprocess.Popen('dir', shell=True, stdout=subprocess.PIPE ,stdin=subprocess.PIPE ,stderr=subprocess.PIPE)
- print(res.stdout.read().decode('gbk'))
- '''
- 输出:
- 驱动器 F 中的卷没有标签。
- 卷的序列号是 7649-38F3
- F:\PyCharm 2018.2.3\PycharmProjects\chen\day15 的目录
- 2018/12/10 20:00 <DIR> .
- 2018/12/10 20:00 <DIR> ..
- 2018/12/10 20:00 219 demo.py
- 2018/12/10 18:47 987 TCP客户端.py
- 2018/12/10 18:47 986 TCP客户端1.py
- 2018/12/10 18:47 2,148 TCP服务端.py
- 2018/12/10 19:44 390 UDP客户端.py
- 2018/12/10 19:44 1,755 UDP服务端.py
- 6 个文件 6,485 字节
- 2 个目录 257,141,366,784 可用字节
- '''
python之路(8)常用模块的更多相关文章
- Python 之路 Day5 - 常用模块学习
本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...
- Python之路,Day5 - 常用模块学习 (转载Alex)
本节大纲: 模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configpars ...
- python 之路 day5 - 常用模块
模块介绍 time &datetime模块 random os sys shutil json & picle shelve xml处理 yaml处理 configparser has ...
- 第六章:Python基础の反射与常用模块解密
本课主题 反射 Mapping 介绍和操作实战 模块介绍和操作实战 random 模块 time 和 datetime 模块 logging 模块 sys 模块 os 模块 hashlib 模块 re ...
- Python之路,Day21 - 常用算法学习
Python之路,Day21 - 常用算法学习 本节内容 算法定义 时间复杂度 空间复杂度 常用算法实例 1.算法定义 算法(Algorithm)是指解题方案的准确而完整的描述,是一系列解决问题的 ...
- Python成长之路(常用模块学习)
Python 拥有很多很强大的模块 主要写一下常用的几个吧 大概就是这些内容了 模块介绍 time &datetime模块 random os sys shutil json & pi ...
- Python学习之路13☞常用模块
一 time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行“type(t ...
- python学习笔记之常用模块(第五天)
参考老师的博客: 金角:http://www.cnblogs.com/alex3714/articles/5161349.html 银角:http://www.cnblogs.com/wupeiqi/ ...
- python之路8-内置模块介绍
time & datetime模块 1 #_*_coding:utf-8_*_ 2 __author__ = 'Alex Li' 3 4 import time 5 6 7 # print(t ...
- python学习日记(常用模块)
模块概念 什么是模块 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用python编写的代 ...
随机推荐
- .net core 命令行(仅作记录)
命令大全:dotnet 命令 创建NuGet包:如何使用 .NET Core 命令行接口 (CLI) 工具创建 NuGet 包
- SQLServer之创建数据库快照
创建数据库快照注意事项 语法:set transaction isolation level snapshot; 指定事务中任何语句读取的数据都将是在事务开始时便存在的数据的事务上一致的版本. 事务只 ...
- IBM developer:Kafka ACLs
Overview In Apache Kafka, the security feature is supported from version 0.9. When Kerberos is enabl ...
- flask-cache报错No module named 'flask.ext;解决方案
找到flask-cache包中的jinja2ext.py,将from flask.ext.cache import make_template_fragment_key改为from flask_cac ...
- jQuery的siblings方法
在使用siblings方法的时候,发现p标签,选中是没有效果的 解决:在w3c中测试也发现是没有效果的,也没有其他的特殊说明,于是度娘之后发现: siblings()获取的是当前标签元素的所有同辈的标 ...
- centos 网卡状态
由于ifconfig命令没法看到网卡的一些状态, 以下有5种方法查看网卡状态,是否连通网线 1)# dmesg | grep eth.....e1000: eth0 NIC Link is Up 10 ...
- 第二章 Python基本图形绘制
2.1 深入理解Python语言 Python语言是通用语言 Python语言是脚本语言 Python语言是开源语言 Python语言是跨平台语言 Python语言是多模型语言 Python的特点与优 ...
- 洛谷-p4555
题意:给你一个串,问你以i结尾的回文串加上以i+1开头的回文串的最大长度 解题思路:回文自动机板子题,记录下每次正着添加字符的时候,当前字符能够到达的最大回文子串的长度和倒着添加字符的时候,能够到达的 ...
- 《css世界》笔记之流、元素与基本尺寸
1. 块级元素 基本特性:就是一个水平流上只能单独显示一个元素,多个块级元素则换行显示. 块级元素和"display 为block 的元素"不是一个概念,display:list- ...
- “理了么”软件特点NABCD个人分析
在这里我就主要对此软件的‘A’(做法)和‘B’(好处)两方面进行分析. “A”:我们的软件为顾客和商家分别提供一种账户,分别登陆后会显示不同的界面. 1.用户界面:拥有“理发店”.“订单“.”和“我的 ...