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 configparserconfig = 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 configparserconfig = 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 configparserconfig = 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 hashlib23 m=hashlib.md5()# m=hashlib.sha256()45 m.update('hello'.encode('utf8'))6 print(m.hexdigest())  #5d41402abc4b2a76b9719d911017c59278 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 alexprint('===>',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 shelvef=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 logginglogging.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模块五个级别

python常用模块(二)相关推荐

  1. python常用模块大全总结-常用python模块

    广告关闭 2017年12月,云+社区对外发布,从最开始的技术博客到现在拥有多个社区产品.未来,我们一起乘风破浪,创造无限可能. python常用模块什么是模块? 常见的场景:一个模块就是一个包含了py ...

  2. 对于python来说、一个模块就是一个文件-python常用模块

    python常用模块 什么是模块? 常见的场景:一个模块就是一个包含了python定义和声明的文件,文件名就是模块名字加上.py的后缀. 但其实import加载的模块分为四个通用类别: 1 使用pyt ...

  3. python用什么来写模块-Python常用模块——模块介绍与导入

    Python常用模块--模块介绍与导入 一.什么是模块? 在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护. 为了编写可维护的代码,我们把很多函数分组,分 ...

  4. python常用模块-调用系统命令模块(subprocess)

    python常用模块-调用系统命令模块(subprocess) 作者:尹正杰 版权声明:原创作品,谢绝转载!否则将追究法律责任. subproces基本上就是为了取代os.system和os.spaw ...

  5. Python 常用模块大全

    Python 常用模块大全(整理) OS 模块 #os模块就是对操作系统进行操作,使用该模块必须先导入模块: import os #getcwd() 获取当前工作目录(当前工作目录默认都是当前文件所在 ...

  6. 实战篇一 python常用模块和库介绍

    # -_-@ coding: utf-8 -_-@ -- Python 常用模块和库介绍 第一部分:json模块介绍 import json 将一个Python数据结构转换为JSON: dict_ = ...

  7. python常用模块之shelve模块

    python常用模块之shelve模块 shelve模块是一个简单的k,v将内存中的数据通过文件持久化的模块,可以持久化任何pickle可支持的python数据类型 我们在上面讲json.pickle ...

  8. Python常用模块——目录

    Python常用模块学习 Python模块和包 Python常用模块time & datetime &random 模块 Python常用模块os & sys & sh ...

  9. Python常用模块集锦

    常用模块主要分为以下几类(缺失的后续再补充): 时间转换 时间计算 序列化和反序列化:json,pickle 编解码:unicode,base64 加解密:md5,sha1,hmac_sha1,aes ...

  10. Python+常用模块(2).md

    Python 常用模块 1. random模块 1.1 导入模块 import random 1.2 random.random() 生成一个从0到1的随机浮点数 1.3 random.uniform ...

最新文章

  1. ccf z字形 java_第三次CCF计算机软件能力认证题目:Z字形扫描
  2. 每日一皮:996标配工位原来是这样的!
  3. python【接上篇】
  4. 推荐一个免费的屏幕取色器,鼠标放到的位置自动显示RGB
  5. 对android中ActionBar中setDisplayHomeAsUpEnabled和setHomeButtonEnabled和setDisplayShowHomeEnabled方法的理解
  6. iOS-夜间模式(换肤设置)
  7. JAVA常用的XML解析方法
  8. 如何自学python-作为一个Python自学者,怎样学好Python?
  9. Easy-rules使用介绍
  10. quartz 的job中获取到applicationContext
  11. CarMaker中关于交通目标行人横穿的问题
  12. 关于《训练指南》中的“翻棋子游戏”
  13. 第六章 平均绝对误差(MAE)与均方根误差(RMSE)
  14. CSS基础教程17篇 [翻译Htmldog]
  15. (附源码课件)10款Java小游戏满足你各种需求
  16. 多多客支持微信公众号,正式开放公测!
  17. 《车载图像采集仿真应用指南》之基于图像采集的座舱测试
  18. linux系统时间编程(2) 各种时间标准GMT、UTC、世界时、TAI
  19. django3.2连接虚拟机里的openGauss
  20. HSI Dataset Visualization:Indian Pines---Python Spectral

热门文章

  1. python 测试字符串类型_【教程】如何用Python中的chardet去检测字符编码类型
  2. c语言编译器_学C语言写自己的K语言:编译器词法分析。
  3. 微型计算机字,在微型计算机的汉字系统中,一个汉字的内码占 – 手机爱问
  4. username is marked non-null but is null
  5. Linux(Centos7)安装Docker
  6. Struts2-day2总结
  7. 文件IO-Properties
  8. spring boot+jpa+MySQL格式化返回数据中实体对象对应的日期格式
  9. Visual C++——修改框体背景颜色
  10. Applese 的取石子游戏