一.json模块
作用:
用于【字符串】和 【python基本数据类型】 间进行转换
Python的Json模块序列化与反序列化的过程分别是 encoding和 decoding。
encoding 把一个Python对象编码转换成Json字符串;decoding 把Json格式字符串解码转换成Python对象。
与pickle区别:
json是可以在不同语言之间交换数据的,而pickle只在python之间使用
json只能序列化最基本的数据类型,而pickle可以序列化所有的数据类型,包括类,函数都可以序列化
函数:
dump --序列化python数据类型对象为JOSN格式的类文件对象,dump 列表-》字符串 -》 类文件对象
load --从josn类文件对象中反序列为PYTHON数据类型对象, 打开文件=》读取内容=》python数据类型如(列表、字典)
dumps --序列化python数据类型对象为字符串格式的josn对象,python数据类型如(列表、字典)-》JOSN字符串
loads --将josn字符串反序列化为PYTHON数据类型,josn字符-》python数据类型如(列表、字典)
举例:
import josn #序列化PYTHON数据类型为JSON格式的类文件并写入 dic = {'k1':1,'k2':2} json.dump(dic,open('db','w')) #从类文件中反序列化为python数据对象 r = json.load(open('db','r')) print(r)
import json #将PYTHON对象序列化为字符串格式的JOSN对象 li = ["a","b","c"] result = json.dumps(li) print(result,type(result))
#运行结果
["a", "b", "c"] <class 'str'>
import json li = '[1,2,3,4]' #将字符串反序列化为python数据对象 result = json.loads(li) print(result,type(result))
#运行结果
[1, 2, 3, 4] <class 'list'>
注:反序列化时注意字典内部要使用双引号 ("")
2. 正常显示json内容
JSON是一个很棒的序列格式,如今广泛应用在API和web服务中,但是很难用裸眼来看大数据量的JSON,它们很长,还在一行里。
可以用参数 indent
来更好地打印JSON数据,这在跟 REPL或是日志打交道的时候很有用:
>>> import json >>> print(json.dumps(data)) # No indention {"status": "OK", "count": 2, "results": [{"age": 27, "name": "Oz", "lactose_intolerant": true}, {"age": 29, "name": "Joe", "lactose_intolerant": false}]} >>> print(json.dumps(data, indent=2)) # With indention { "status": "OK", "count": 2, "results": [ { "age": 27, "name": "Oz", "lactose_intolerant": true }, { "age": 29, "name": "Joe", "lactose_intolerant": false } ] }
二.configparser
作用:
configparser用于处理特定格式的文件,其本质上是利用open来操作文件
指定格式:

# 注释1 ; 注释2 [section1] # 节点 k1 = v1 # 值 k2:v2 # 值 [section2] # 节点 k1 = v1 # 值 指定格式
函数:
sections() --返回所有配置节点的名字
has_section(section) --返回给定节点是否存在
has_option(section, option) --返回指定选项是否在指定的节点中
options(section) --返回指定节点的选项列表
read(filenames, encoding=None) --读取解析配置文件
get(section, option, raw=False, vars=None, fallback=_UNSET) --以字符串格式返回指定节点选项的值
getint(section, options, raw=False, vars=None, fallback=_UNSET) --将返回指定节点选项的值转化为int类型
items(section=_UNSET, raw=False, vars=None) --以元组格式返回指定节点的所有键值对
remove_section(section) --移除指定节点包括其下选项
remove_option(section, option) --移除指定节点下的键值
set(section, option, value) --设置指定节点下的选项,需写入文件方可生效
write(fp, space_around_delimiters=True) --写入配置文件
举例:
#!/usr/bin/env python # -*- coding:utf-8 -*- import configparser conf = configparser.ConfigParser() conf.read('config.txt') result = conf.sections() print(result) sub_res = conf.options('test') print(sub_res) #获取节点下的内容 conf = configparser.ConfigParser() conf.read('config.txt') result = conf.get('test','name') print(result) #检查节点 conf = configparser.ConfigParser() conf.read('config.txt') file_check = conf.has_section('test') print(file_check) #添加节点 conf.add_section('test3') conf.write(open('config.txt','w')) #删除节点 conf.remove_section('test2') conf.write(open('config.txt','w')) #以字符串格式返回指定节点选项的值 conf = configparser.ConfigParser() conf.read('config.txt') result = conf.get('test','name') print(result,type(result)) #将返回指定节点选项的值转化为int类型 conf = configparser.ConfigParser() conf.read('config.txt') result = conf.getint('test','age') print(result,type(result)) #以元组格式返回指定节点的所有键值对 conf = configparser.ConfigParser() conf.read("config.txt") result = conf.items("test") print(result)
三.XML
功能:
XML是实现不同语言或程序之间进行数据交换的协议
格式:

<data> <country name="Liechtenstein"> <rank updated="yes">2</rank> <year>2023</year> <gdppc>141100</gdppc> <neighbor direction="E" name="Austria" /> <neighbor direction="W" name="Switzerland" /> </country> <country name="Singapore"> <rank updated="yes">5</rank> <year>2026</year> <gdppc>59900</gdppc> <neighbor direction="N" name="Malaysia" /> </country> <country name="Panama"> <rank updated="yes">69</rank> <year>2026</year> <gdppc>13600</gdppc> <neighbor direction="W" name="Costa Rica" /> <neighbor direction="E" name="Colombia" /> </country> </data>
XML模块支持两个类;
-
ElementTree代指整个xml文档树
-
Element 指一个树节点
-
每个Elenment都有相关联的属性:
'tag' - 标签,节点名称.
'attributes' - 节点属性.
'text' - 节点的文本内容.
'tail' - 节点结束标记.
class Element()
函数:
makeelement(self, tag, attrib) --创建新的节点
append(self, subelement) --向节点中追加内容
insert(self, index, subelement) --在子节点下插入节点
remove(self, subelement) --删除匹配的子节点
getchildren(self) --获得所有子节点
find(self, path, namespaces=None) --找到第一个匹配名字或者路径的节点
findtext(self, path, default=None, namespaces=None) --找到第一个匹配指定tag或path的文本
findall(self, path, namespaces=None) --找到所有匹配tag 或path的节点
get(self, key, default=None) --获得所有节点的属性
set(self, key, value) --设置节点属性
keys(self) --获得节点键值
SubElement(parent, tag, attrib={}, **extra) --创建子节点并添加到父节点中
举例:
#!/usr/bin/env python # -*- coding:utf-8 -*- from xml.etree import ElementTree as ET #创建子节点 node = ET.parse('test.xml') root = node.getroot() son = root.makeelement("t1", {'t1': 'v1'}) val = son.makeelement("t2", {'t2': 'v2'}) root.append(son) son.append(val) node.write('test.xml') #设置指定标签属性 valu = ET.parse('xmltest.xml') root = valu.getroot() for i in root.iter('year'): new_year = int(i.text) + 1 i.text = str(new_year) i.set('time','time') del i.attrib['time'] valu.write('xmltest.xml') #返回包含所有元素属性键的列表 info = ET.parse('insert.xml') root = info.getroot() for i in root.iter('country'): rank = i.find('rank') key = rank.keys() print(key) #返回指定节点属性 info = ET.parse('insert.xml') root = info.getroot() for i in root.iter('country'): allarr = i.get('name') print(allarr) #查找匹配tag的文本内容 #车次发车时间表 res =requests.get("http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=K234&UserID=") result = res.text from xml.etree import ElementTree as ET init = ET.XML(result) for i in init.iter("TrainDetailInfo"): print(i.find("TrainStation").text,i.find("ArriveTime").text,i.find("StartTime").text,i.find("KM").text) #在节点下插入子节点 rtree = ET.parse('test.xml') root=rtree.getroot() tree = ET.SubElement(root,'book') son = ET.Element('name') son.text = 'insert,test' tree.insert(2,son) rtree.write('insert.xml')
删除节点
from xml.etree import ElementTree as ET ############ 解析文件方式 ############ # 直接解析xml文件 tree = ET.parse("xo.xml") # 获取xml文件的根节点 root = tree.getroot() ############ 操作 ############ # 顶层标签 print(root.tag) # 遍历data下的所有country节点 for country in root.findall('country'): # 获取每一个country节点下rank节点的内容 rank = int(country.find('rank').text) if rank > 50: # 删除指定country节点 root.remove(country) ############ 保存文件 ############ tree.write("newnew.xml", encoding='utf-8') 解析文件方式打开,删除,保存
class ElementTree()
函数 :
getroot() --获取所有节点内容
parse(self, source, parser=None) -- 加载XML文件到elementtree中

from xml.etree import ElementTree as ET # 直接解析xml文件 tree = ET.parse("xo.xml") # 获取xml文件的根节点 root = tree.getroot()
创建XML文件

from xml.etree import ElementTree as ET # 创建根节点 root = ET.Element("famliy") # 创建节点大儿子 son1 = ET.Element('son', {'name': '儿1'}) # 创建小儿子 son2 = ET.Element('son', {"name": '儿2'}) # 在大儿子中创建两个孙子 grandson1 = ET.Element('grandson', {'name': '儿11'}) grandson2 = ET.Element('grandson', {'name': '儿12'}) son1.append(grandson1) son1.append(grandson2) # 把儿子添加到根节点中 root.append(son1) root.append(son1) tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False) 创建方式(一)

from xml.etree import ElementTree as ET # 创建根节点 root = ET.Element("famliy") # 创建大儿子 # son1 = ET.Element('son', {'name': '儿1'}) son1 = root.makeelement('son', {'name': '儿1'}) # 创建小儿子 # son2 = ET.Element('son', {"name": '儿2'}) son2 = root.makeelement('son', {"name": '儿2'}) # 在大儿子中创建两个孙子 # grandson1 = ET.Element('grandson', {'name': '儿11'}) grandson1 = son1.makeelement('grandson', {'name': '儿11'}) # grandson2 = ET.Element('grandson', {'name': '儿12'}) grandson2 = son1.makeelement('grandson', {'name': '儿12'}) son1.append(grandson1) son1.append(grandson2) # 把儿子添加到根节点中 root.append(son1) root.append(son1) tree = ET.ElementTree(root) tree.write('oooo.xml',encoding='utf-8', short_empty_elements=False)

from xml.etree import ElementTree as ET # 创建根节点 root = ET.Element("famliy") # 创建节点大儿子 son1 = ET.SubElement(root, "son", attrib={'name': '儿1'}) # 创建小儿子 son2 = ET.SubElement(root, "son", attrib={"name": "儿2"}) # 在大儿子中创建一个孙子 grandson1 = ET.SubElement(son1, "age", attrib={'name': '儿11'}) grandson1.text = '孙子' et = ET.ElementTree(root) #生成文档对象 et.write("test.xml", encoding="utf-8", xml_declaration=True, short_empty_elements=False)
四.requests
简介:
Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,
变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作
- 安装模块
pip install requests
- 用法
usage:无参数
>>> import requests
>>> r = requests.get('https://www.python.org')
>>> r.status_code
200
>>> 'Python is a programming language' in r.content
True
... or POST:
>>> payload = dict(key1='value1', key2='value2')
>>> r = requests.post('http://httpbin.org/post', data=payload)
>>> print(r.text)
{
...
"form": {
"key2": "value2",
"key1": "value1"
},
...
}
import requests
#有参数实例 payload = {'key1': 'value1', 'key2': 'value2'} ret = requests.get("http://httpbin.org/get", params=payload) print(ret.url) print(ret.text)
HTTP请求和XML实例

import requests from xml.etree import ElementTree as ET r = requests.get('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508') result = r.text # 解析XML格式内容 node = ET.XML(result) # 获取内容 if node.text == "Y": print("在线") else: print("离线")

import requests #车次发车时间表 res = requests.get("http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=K234&UserID=") result = res.text from xml.etree import ElementTree as ET init = ET.XML(result) for i in init.iter("TrainDetailInfo"): print(i.find("TrainStation").text,i.find("ArriveTime").text,i.find("StartTime").text,i.find("KM").text)
五.shutil
功能:
高级的 文件、文件夹、压缩包 处理模块
函数 :
copyfile(src, dst, *, follow_symlinks=True) --从源拷贝到目的文件
copymode(src, dst, *, follow_symlinks=True) --将权限位从src复制到dst
copyfileobj(fsrc, fdst, length=16*1024) --将文件内容拷贝到另一个文件中
copystat(src, dst, *, follow_symlinks=True) --将权限位、 最后存取时间、 最后修改时间和标志从src复制到dst
copy(src, dst, *, follow_symlinks=True) --将src文件复制到文件或dst目录
copy2(src, dst, *, follow_symlinks=True) --将文件的所有属性拷贝到dst
ignore_patterns(*patterns) --此工厂函数创建一个函数,它可以作为可调用用于copytree()的ignore参数,忽略匹配glob风格的模式的文件和目录
copytree(src, dst, symlinks=False, ignore=None,
copy_function=copy2,ignore_dangling_symlinks=False) --以递归方式复制以src为根的整个目录树
rmtree(path, ignore_errors=False, onerror=None) --删除整个目录树
move(src, dst, copy_function=copy2) --以递归方式移动文件或目录(src)到另一个位置(dst)
make_archive(base_name, format, root_dir=None, base_dir=None, verbose=0,
dry_run=0, owner=None, group=None, logger=None) --创建压缩包并返回文件路径
举例:

#!/usr/bin/env python # -*- coding:utf-8 -*- import shutil #拷贝文件内容到dst文件 shutil.copyfileobj(open('config.txt','r'),open('copyfile.txt','w')) #从源拷贝到目的文件 shutil.copyfile('config.txt','config2.txt') #将权限位从src复制到dst shutil.copymode('config.txt','config2.txt') #将权限位、 最后存取时间、 最后修改时间和标志从src复制到dst shutil.copystat('config.txt','config2.txt') #将src文件复制到文件或dst目录 shutil.copy('config.txt','config2.txt') #递归的去拷贝文件夹,忽略匹配的文件和目录 shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*')) #递归的去删除文件 shutil.rmtree('test') #以递归方式移动文件或目录(src)到另一个位置(dst) shutil.move('test','dsttest') #创建压缩包并返回文件路径 ret = shutil.make_archive("filename", 'gztar', root_dir='/Users/wupeiqi/Downloads/test')
六.subprocess
功能:
用于执行复杂的系统命令
函数:
call(*popenargs, **kwargs) --执行命令并返回结果
check_call --执行命令如果返回0则返回执行结果
subprocess.Popen(...) --用于执行复杂的系统命令
参数:
- args:shell命令,可以是字符串或者序列类型(如:list,元组)
- bufsize:指定缓冲。0 无缓冲,1 行缓冲,其他 缓冲区大小,负值 系统缓冲
- stdin, stdout, stderr:分别表示程序的标准输入、输出、错误句柄
- preexec_fn:只在Unix平台下有效,用于指定一个可执行对象(callable object),它将在子进程运行之前被调用
- close_sfs:在windows平台下,如果close_fds被设置为True,则新创建的子进程将不会继承父进程的输入、输出、错误管道。
所以不能将close_fds设置为True同时重定向子进程的标准输入、输出与错误(stdin, stdout, stderr)。 - shell:同上
- cwd:用于设置子进程的当前目录
- env:用于指定子进程的环境变量。如果env = None,子进程的环境变量将从父进程中继承。
- universal_newlines:不同系统的换行符不同,True -> 同意使用
- startupinfo与createionflags只在windows下有效
将被传递给底层的CreateProcess()函数,用于设置子进程的一些属性,如:主窗口的外观,进程的优先级等等
举例:
#!/usr/bin/env python # -*- coding:utf-8 -*- import subprocess #--执行命令并返回结果 subprocess.call('ipconfig') #--执行命令如果返回0则返回执行结果 subprocess.check_call('nslookup www.baidu.com') #创建目录 obj = subprocess.Popen("mkdir t3", shell=True, cwd='/home/dev',)

obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) obj.stdin.write("print(1) ") obj.stdin.write("print(2)") obj.stdin.close()

import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) obj.stdin.write("print(1) ") obj.stdin.write("print(2)") out_error_list = obj.communicate() print(out_error_list)

import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) obj.stdin.write("print(1) ") obj.stdin.write("print(2)") out_error_list = obj.communicate() print(out_error_list)

import subprocess obj = subprocess.Popen(["python"], stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, universal_newlines=True) out_error_list = obj.communicate('print("hello")') print(out_error_list)