python之路(8)常用模块

时间:2023-03-09 02:41:14
python之路(8)常用模块

 

目录


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 可用字节
'''