1、json&pickle 模块
json 跨语言、体积小但只支持int、str、list、tuple、dict格式的数据
pickle 专为python设计,支持python的所有数据类型,但储存数据占用空间大。
Json 模块提供了四个方法: dumps、dump、loads、load
>>> import json >>> dict = {"name":"Tom", "age":23} >>> json.dumps(dict) # 字典 '{"name": "Tom", "age": 23}'
a = {"name":"Tom", "age":23}
with open("test.json", "w", encoding='utf-8') as f:
json.dump(a)
2.loads 和 load
>>> json.loads('{"name":"Tom", "age":23}') {'age': 23, 'name': 'Tom'}
with open("test.json", "r", encoding='utf-8') as f: aa = json.loads(f.read()) f.seek(0) bb = json.load(f) # 与 json.loads(f.read()) print(aa) print(bb) # 输出: {'name': 'Tom', 'age': 23} {'name': 'Tom', 'age': 23}
2、shelve模块
Shelve是对象持久化保存方法,将对象保存到文件里面,缺省(即默认)的数据存储文件是二进制的。
使用时,只需要使用open函数获取一个shelf对象,然后对数据进行增删改查操作,在完成工作、并且将内存存储到磁盘中,最后调用close函数变回将数据写入文件。import shelve s = shelve.open('test_shelf') s['kk'] = {'int': 10, 'float': 9.5, 'String': 'Sample data'} s['MM'] = [1, 2, 3] s.close()
3、configparser
ConfigParser 是用来读取配置文件的包。配置文件的格式如下:中括号“[ ]”内包含的为section。section 下面为类似于key-value 的配置内容。
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root host_port = 69 [concurrent] thread = 10 processor = 20
括号“[ ]”内包含的为section。紧接着section 为类似于key-value 的options 的配置内容。
ConfigParser 初始化对象
使用ConfigParser 首选需要初始化实例,并读取配置文件:
import configparser
config = configparser.ConfigParser()
config.read("ini", encoding="utf-8")
ConfigParser 常用方法
1.获取所用的section节点
# 获取所用的section节点 print(config.sections()) #运行结果 # ['db', 'concurrent']
2.获取指定section 的options。即将配置文件某个section 内key 读取到列表中:
r = config.options("db")
print(r)
#运行结果
# ['db_host', 'db_port', 'db_user', 'db_pass', 'host_port']
3.获取指点section下指点option的值
r = config.get("db", "db_host")
# r1 = config.getint("db", "k1") #将获取到值转换为int型
# r2 = config.getboolean("db", "k2" ) #将获取到值转换为bool型
# r3 = config.getfloat("db", "k3" ) #将获取到值转换为浮点型
print(r)
#运行结果
# 127.0.0.1
4.获取指点section的所用配置信息
r = config.items("db")
print(r)
#运行结果
#[('db_host', '127.0.0.1'), ('db_port', '69'), ('db_user', 'root'), ('db_pass', 'root'), ('host_port', '69')]
5.修改某个option的值,如果不存在则会出创建
# 修改某个option的值,如果不存在该option 则会创建
config.set("db", "db_port", "69") #修改db_port的值为69
config.write(open("ini", "w"))
[db] db_host = 127.0.0.1 db_port = 69 db_user = root db_pass = root [concurrent] thread = 10 processor = 20
6.检查section或option是否存在,bool值
config.has_section("section") #是否存在该section
config.has_option("section", "option") #是否存在该option
7.添加section 和 option
if not config.has_section("default"): # 检查是否存在section
config.add_section("default")
if not config.has_option("default", "db_host"): # 检查是否存在该option
config.set("default", "db_host", "1.1.1.1")
config.write(open("ini", "w"))
8.删除section 和 option
config.remove_section("default") #整个section下的所有内容都将删除
config.write(open("ini", "w"))
运行结果9.写入文件
以下的几行代码只是将文件内容读取到内存中,进过一系列操作之后必须写回文件,才能生效。
写回文件的方式如下:(使用configparser的write方法)
config.write(open("ini", "w"))
4、logging模块
import logging logging.basicConfig(level = logging.INFO,format = '%(asctime)s - %(name)s - %(levelname)s - %(message)s') logger = logging.getLogger(__name__)
将日志同时输出到屏幕和文件
import logging logger = logging.getLogger(__name__) logger.setLevel(level = logging.INFO) handler = logging.FileHandler("log.txt") handler.setLevel(logging.INFO) formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') handler.setFormatter(formatter) console = logging.StreamHandler() console.setLevel(logging.INFO) logger.addHandler(handler) logger.addHandler(console) logger.info("Start print log") logger.debug("Do something") logger.warning("Something maybe fail.") logger.info("Finish")
5、re模块
. 匹配除\n外的任意字符 ^ 匹配字符开头 $ 匹配字符结尾 * 匹配前一个字符0次或多次 + 匹配前一个字符1次或多次 ? 匹配前一个字符0次或1次 {m} 匹配前一个字符m次 {n,m} 匹配前一个字符n~m次 | 匹配‘|’左或右的字符 (...) 分组匹配 \A 只从字符开头匹配 \Z 匹配字符结尾 \d 匹配数字0-9 \D 匹配非数字 \w 匹配【A-Za-z0-9】 \W 匹配非【A-Za-z0-9】 \s 匹配空白字符\n\t\r '(?P<规则>)....' 分组匹配
1.compile()
编译正则表达式模式,返回一个对象的模式。
import re tt = "Tina is a good girl, she is cool, clever, and so on..." rr = re.compile(r'\w*oo\w*') print(rr.findall(tt)) #查找所有包含'oo'的单词
2、match()
决定RE是否在字符串刚开始的位置匹配。
3、search()
re.search(pattern, string, flags=0)
re.search函数会在字符串内查找模式匹配,只要找到第一个匹配然后返回,如果字符串没有匹配,则返回None。
4、findall()
re.findall遍历匹配,可以获取字符串中所有匹配的字符串,返回一个列表。
re.findall(pattern, string, flags=0)
6、split()
按照能够匹配的子串将string分割后返回列表。
可以使用re.split来分割字符串,如:re.split(r'\s+', text);将字符串按空格分割成一个单词列表。
re.split(pattern, string[, maxsplit])
maxsplit用于指定最大分割次数,不指定将全部分割。
7、sub()
使用re替换string中每一个匹配的子串后返回替换后的字符串。
re.sub(pattern, repl, string, count)

浙公网安备 33010602011771号