configparser模块
学习python中有什么不懂的地方,小编这里推荐加小编的python学习群:895 817 687有任何不懂的都可以在里面交流,还有很好的视频教程pdf学习资料,大家一起学习交流!
用于生成和修改常见配置文档
配置文件
[default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
[bitbucket.org]
user = hg
[topsecret.server.com]
port = 50022
forwardx11 = no
用python生成这样的一个配置文档
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'] = {'port':'50022',
'Forwardx11':'no'}
with open('example.ini','w') as configfile:
config.write(configfile)
读取
import configparser
config = configparser.ConfigParser()
print(config.read('example.ini'))
#查看所有的标题
print(config.sections())
#['default', 'bitbucket.org', 'topsecret.server.com']
#查看标题section1下所有key=value的key
options = config.options('default')
print(options)
#['serveraliveinterval', 'compression', 'compressionlevel']
#查看标题section1下所有key=value的(key,value)格式
items_list = config.items('topsecret.server.com')
print(items_list)
#[('port', '50022'), ('forwardx11', 'no')]
增删改查
import configparser
config = configparser.ConfigParser()
config.read('example.ini',encoding = 'utf-8')
#删除整个标题
config.remove_section('bitbucket.org')
#删除标题下的option
config.remove_option('topsecret.server.com','port')
#添加一个标题
config.add_section('info')
#在标题下添加options
config.set('info','name','derek')
#判断是否存在
print(config.has_section('info')) #True
print(config.has_option('info','name')) #True
#将修改的内容存入文件
config.write(open('new_example.ini','w'))
#修改后的文件
[default]
serveraliveinterval = 45
compression = yes
compressionlevel = 9
[topsecret.server.com]
forwardx11 = no
[info]
name = derek
hashlib模块
hash:一种算法 ,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
三个特点:
1.内容相同则hash运算结果相同,内容稍微改变则hash值则变
2.不可逆推
3.相同算法:无论校验多长的数据,得到的哈希值长度固定。
1 import hashlib
2
3 m=hashlib.md5()# m=hashlib.sha256()
4
5 m.update('hello'.encode('utf8'))
6 print(m.hexdigest()) #5d41402abc4b2a76b9719d911017c592
7
8 m.update('alvin'.encode('utf8'))
9
10 print(m.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af
11
12 m2=hashlib.md5()
13 m2.update('helloalvin'.encode('utf8'))
14 print(m2.hexdigest()) #92a7e713c30abbb0319fa07da2a5c4af
15
16 '''
17 注意:把一段很长的数据update多次,与一次update这段长数据,得到的结果一样
18 但是update多次为校验大文件提供了可能。
re模块
# 正则匹配
import re
# \w与\W 字母数字下划线
print(re.findall('\w', 'hello derek \n 123'))
print(re.findall('\W', 'hello derek \n 123'))
# ['h', 'e', 'l', 'l', 'o', 'd', 'e', 'r', 'e', 'k', '1', '2', '3']
# [' ', ' ', '\n', ' ']
# \s与\S 匹配任意空白字符
print(re.findall('\s', 'hello egon 123')) # [' ', ' ', ' ', ' ']
print(re.findall('\S', 'hello egon 123')) # ['h', 'e', 'l', 'l', 'o', 'e', 'g', 'o', 'n', '1', '2', '3']
# \n \t都是空,都可以被\s匹配
print(re.findall('\s', 'hello \n egon \t 123')) # [' ', '\n', ' ', ' ', '\t', ' ']
# \n与\t
print(re.findall(r'\n', 'hello egon \n123')) # ['\n']
print(re.findall(r'\t', 'hello egon\t123')) # ['\n']
# \d与\D
print(re.findall('\d', 'hello egon 123')) # ['1', '2', '3']
print(re.findall('\D', 'hello egon 123')) # ['h', 'e', 'l', 'l', 'o', ' ', 'e', 'g', 'o', 'n', ' ']
# \A与\Z \A 匹配字符串开始 \Z 匹配字符串结束
print(re.findall('\Ahe', 'hello egon 123')) # ['he'],\A==>^
print(re.findall('123\Z', 'hello egon 123')) # ['he'],\Z==>$
# ^与$
print(re.findall('^h', 'hello egon 123')) # ['h']
print(re.findall('3$', 'hello egon 123')) # ['3']
# 重复匹配:| . | * | ? | .* | .*? | + | {n,m} |
# . 匹配任意字符,除了换行符,除非re.DOTALL标记
print(re.findall('a.b', 'a1b')) # ['a1b']
# a和b中间匹配任意一个字符
print(re.findall('a.b', 'a1b a*b a b aaab')) # ['a1b', 'a*b', 'a b', 'aab']
print(re.findall('a.b', 'a\nb')) # []
print(re.findall('a.b', 'a\nb', re.S)) # ['a\nb']
print(re.findall('a.b', 'a\nb', re.DOTALL)) # ['a\nb']同上一条意思一样
print(re.findall('a...b', 'a123b')) # ['a123b']
# *匹配*号前的字符0次或多次
print(re.findall('ab*', 'bbbbbbb')) # []
print(re.findall('ab*', 'a')) # ['a']
print(re.findall('ab*', 'abbbb')) # ['abbbb']
print(re.findall('ab*', 'abababbabbbb')) # ['ab', 'ab', 'abb', 'abbbb']
# ? 匹配前一个字符1次或0次
print(re.findall('ab?', 'a')) # ['a']
print(re.findall('ab?', 'abbb')) # ['ab']
# 匹配所有包含小数在内的数字
print(re.findall('\d+\.?\d*', "asdfasdf123as1.13dfa12adsf1asdf3")) # ['123', '1.13', '12', '1', '3']
# .*默认为贪婪匹配
print(re.findall('a.*b', 'a1b22222222b')) # ['a1b22222222b']
# .*?为非贪婪匹配:推荐使用
print(re.findall('a.*?b', 'a1b22222222b')) # ['a1b']
# + 匹配前一个字符1次或多次
print(re.findall('ab+', 'abbaabb')) # ['abb', 'abb']
print(re.findall('ab+', 'abbb')) # ['abbb']
# {n,m} 匹配前一个字符n到m次
print(re.findall('ab{2}', 'abbb')) # ['abb']
print(re.findall('ab{2,4}', 'abbb')) # ['abb']
print(re.findall('ab{1,}', 'abbb')) # 'ab{1,}' ===> 'ab+'
print(re.findall('ab{0,}', 'abbb')) # 'ab{0,}' ===> 'ab*'
# []
print(re.findall('a[1*-]b', 'a1b a*b a-b')) # []内的都为普通字符了,且如果-没有被转意的话,应该放到[]的开头或结尾
print(re.findall('a[^1*-]b', 'a1b a*b a-b a=b')) # []内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[0-9]b', 'a1b a*b a-b a=b')) # []内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[a-z]b', 'a1b a*b a-b a=b aeb')) # []内的^代表的意思是取反,所以结果为['a=b']
print(re.findall('a[a-zA-Z]b', 'a1b a*b a-b a=b aeb aEb')) # []内的^代表的意思是取反,所以结果为['a=b']
# \# print(re.findall('a\\c','a\c')) #对于正则来说a\\c确实可以匹配到a\c,但是在python解释器读取a\\c时,会发生转义,然后交给re去执行,所以抛出异常
print(re.findall(r'a\\c', 'a\c')) # r代表告诉解释器使用rawstring,即原生字符串,把我们正则内的所有符号都当普通字符处理,不要转义
print(re.findall('a\\\\c', 'a\c')) # 同上面的意思一样,和上面的结果一样都是['a\\c']
# (): 匹配括号里面的内容
print(re.findall('ab+', 'ababab123')) # ['ab', 'ab', 'ab']
print(re.findall('(ab)+123', 'ababab123')) # ['ab'],匹配到末尾的ab123中的ab
print(re.findall('(?:ab)+123', 'ababab123')) # findall的结果不是匹配的全部内容,而是组内的内容,?:可以让结果为匹配的全部内容
# |
print(re.findall('compan(?:y|ies)', 'Too many companies have gone bankrupt, and the next one is my company'))
一些方法
# ===========================re模块提供的方法介绍===========================
import re
#1
print(re.findall('e','alex make love') ) #['e', 'e', 'e'],返回所有满足匹配条件的结果,放在列表里
#2
print(re.search('e','alex make love').group()) #e,只到找到第一个匹配然后返回一个包含匹配信息的对象,该对象可以通过调用group()方法得到匹配的字符串,如果字符串没有匹配,则返回None。
#3
print(re.match('e','alex make love')) #None,同search,不过在字符串开始处进行匹配,完全可以用search+^代替match
#4
print(re.split('[ab]','abcd')) #['', '', 'cd'],先按'a'分割得到''和'bcd',再对''和'bcd'分别按'b'分割
#5
print('===>',re.sub('a','A','alex make love')) #===> Alex mAke love,不指定n,默认替换所有
print('===>',re.sub('a','A','alex make love',1)) #===> Alex make love
print('===>',re.sub('a','A','alex make love',2)) #===> Alex mAke love
print('===>',re.sub('^(\w+)(.*?\s)(\w+)(.*?\s)(\w+)(.*?)$',r'\5\2\3\4\1','alex make love')) #===> love make alex
print('===>',re.subn('a','A','alex make love')) #===> ('Alex mAke love', 2),结果带有总共替换的个数
#6
obj=re.compile('\d{2}')
print(obj.search('abc123eeee').group()) #12
print(obj.findall('abc123eeee')) #['12'],重用了obj
shelve模块
shelve模块比pickle模块简单,只有一个open函数,返回类似字典的对象,可读可写;key必须为字符串,而值可以是python所支持的数据类型
import shelve
f=shelve.open(r'sheve.txt')
# f['stu1_info']={'name':'egon','age':18,'hobby':['piao','smoking','drinking']}
# f['stu2_info']={'name':'gangdan','age':53}
# f['school_info']={'website':'http://www.pypy.org','city':'beijing'}
print(f['stu1_info']['hobby'])
f.close()
logging模块
很多程序都有记录日志的需求,并且日志中包含的信息即有正常的程序访问日志,还可能有错误、警告等信息输出,python的logging模块提供了标准的日志接口,你可以通过它存储各种格式的日志,logging的日志可以分为 debug、info、warning、error、critical5个级别
1.模块初始
import logging
logging.warning('wrong password more than 3 times')
logging.critical('server is down')
logging.error('error message')
结果:
WARNING:root:wrong password more than 3 times
CRITICAL:root:server is down
ERROR:root:error message
2.logging模块五个级别