一.序列化
Python中用于序列化的两个模块
- json 用于【字符串】和 【python基本数据类型】 间进行转换
- pickle 用于【python特有的类型】 和 【python基本数据类型】间进行转换
Json模块提供了四个功能:dumps、dump、loads、load
Json.loads()用于将字典,列表形式的字符串转换成相应的字典,列表
Json.dump()将基本数据类型,列表,字典,转换成字符串
pickle模块提供了四个功能:dumps、dump、loads、load
二.安装第三方模块
第1种安装方法:
安装软件管理工具pip3 (python3中自带了pip3)
将pip3添加到环境变量
pip3 install 被安装的东西
第2种安装方法:
下载代码,安装
三.requests模块
Python标准库中提供了:urllib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务。
注:更多见Python官方文档:https://docs.python.org/3.5/library/urllib.request.html#module-urllib.request
Requests 是使用 Apache2 Licensed 许可证的 基于Python开发的HTTP 库,其在Python内置模块的基础上进行了高度的封装,从而使得Pythoner进行网络请求时,变得美好了许多,使用Requests可以轻而易举的完成浏览器可有的任何操作。
1、安装模块
|
1
|
pip3
install requests
|
2、使用模块
更多requests模块相关的文档见:http://cn.python-requests.org/zh_CN/latest/
四.XML模块
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>
1、解析XML
2、操作XML
XML格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作:
由于 每个节点 都具有以上的方法,并且在上一步骤中解析时均得到了root(xml文件的根节点),so 可以利用以上方法进行操作xml文件。
a. 遍历XML文档的所有内容
from xml.etree import ElementTree as ET ############ 解析方式一 ############ """ # 打开文件,读取XML内容 str_xml = open('xo.xml', 'r').read() # 将字符串解析成xml特殊对象,root代指xml文件的根节点 root = ET.XML(str_xml) """ ############ 解析方式二 ############ # 直接解析xml文件 tree = ET.parse("xo.xml") # 获取xml文件的根节点 root = tree.getroot() ### 操作 # 顶层标签 print(root.tag) # 遍历XML文档的第二层 for child in root: # 第二层节点的标签名称和标签属性 print(child.tag, child.attrib) # 遍历XML文档的第三层 for i in child: # 第二层节点的标签名称和内容 print(i.tag,i.text)
b、遍历XML中指定的节点
from xml.etree import ElementTree as ET ############ 解析方式一 ############ """ # 打开文件,读取XML内容 str_xml = open('xo.xml', 'r').read() # 将字符串解析成xml特殊对象,root代指xml文件的根节点 root = ET.XML(str_xml) """ ############ 解析方式二 ############ # 直接解析xml文件 tree = ET.parse("xo.xml") # 获取xml文件的根节点 root = tree.getroot() ### 操作 # 顶层标签 print(root.tag) # 遍历XML中所有的year节点 for node in root.iter('year'): # 节点的标签名称和内容 print(node.tag, node.text)
c、修改节点内容
由于修改的节点时,均是在内存中进行,其不会影响文件中的内容。所以,如果想要修改,则需要重新将内存中的内容写到文件。
d、删除节点
3、创建XML文档
由于原生保存的XML时默认无缩进,如果想要设置缩进的话, 需要修改保存方式:
五.configparser模块
configparser用于处理特定格式的文件,其本质上是利用open来操作文件。
1、获取所有节点
|
1
2
3
4
5
6
|
import configparser
config = configparser.ConfigParser()
config.read('xxxooo',
encoding='utf-8')
ret = config.sections()
print(ret)
|
2、获取指定节点下所有的键值对
|
1
2
3
4
5
6
|
import configparser
config = configparser.ConfigParser()
config.read('xxxooo',
encoding='utf-8')
ret = config.items('section1')
print(ret)
|
3、获取指定节点下所有的建
|
1
2
3
4
5
6
|
import configparser
config = configparser.ConfigParser()
config.read('xxxooo',
encoding='utf-8')
ret = config.options('section1')
print(ret)
|
4、获取指定节点下指定key的值
|
1
2
3
4
5
6
7
8
9
10
11
12
|
import configparser
config = configparser.ConfigParser()
config.read('xxxooo',
encoding='utf-8')
v = config.get('section1', 'k1')
#
v = config.getint('section1', 'k1')
#
v = config.getfloat('section1', 'k1')
#
v = config.getboolean('section1', 'k1')
print(v)
|
5、检查、删除、添加节点
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
|
import configparser
config = configparser.ConfigParser()
config.read('xxxooo',
encoding='utf-8')
#
检查
has_sec = config.has_section('section1')
print(has_sec)
#
添加节点
config.add_section("SEC_1")
config.write(open('xxxooo', 'w'))
#
删除节点
config.remove_section("SEC_1")
config.write(open('xxxooo', 'w'))
|
6、检查、删除、设置指定组内的键值对
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
|
import configparser
config = configparser.ConfigParser()
config.read('xxxooo',
encoding='utf-8')
# 检查has_opt = config.has_option('section1', 'k1')
print(has_opt)
# 删除config.remove_option('section1', 'k1')
config.write(open('xxxooo', 'w'))
# 设置config.set('section1', 'k10', "123")
config.w |
六.shutil模块
高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中
|
1
2
3
|
import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
|
shutil.copyfile(src, dst)
拷贝文件
|
1
|
shutil.copyfile('f1.log', 'f2.log')
|
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变
|
1
|
shutil.copymode('f1.log', 'f2.log')
|
shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
|
1
|
shutil.copystat('f1.log', 'f2.log')
|
shutil.copy(src, dst)
拷贝文件和权限
|
1
2
3
|
import shutil
shutil.copy('f1.log', 'f2.log')
|
shutil.copy2(src, dst)
拷贝文件和状态信息
|
1
2
3
|
import shutil
shutil.copy2('f1.log', 'f2.log')
|
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
|
1
2
3
|
import shutil
shutil.copytree('folder1', 'folder2',
ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
|
import shutil
shutil.copytree('f1', 'f2', symlinks=True, ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
|
1
2
3
|
import shutil
shutil.rmtree('folder1')
|
shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。
|
1
2
3
|
import shutil
shutil.move('folder1', 'folder3')
|
shutil.make_archive(base_name, format,...)
创建压缩包并返回文件路径,例如:zip、tar
创建压缩包并返回文件路径,例如:zip、tar
- base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
如:www =>保存至当前路径
如:/Users/wupeiqi/www =>保存至/Users/wupeiqi/ - format: 压缩包种类,“zip”, “tar”, “bztar”,“gztar”
- root_dir: 要压缩的文件夹路径(默认当前目录)
- owner: 用户,默认当前用户
- group: 组,默认当前组
- logger: 用于记录日志,通常是logging.Logger对象
|
1
2
3
4
5
6
7
8
|
#将
/Users/wupeiqi/Downloads/test 下的文件打包放置当前程序目录
import shutil
ret = shutil.make_archive("wwwwwwwwww", 'gztar',
root_dir='/Users/wupeiqi/Downloads/test')
#将
/Users/wupeiqi/Downloads/test 下的文件打包放置 /Users/wupeiqi/目录
import shutil
ret = shutil.make_archive("/Users/wupeiqi/wwwwwwwwww", 'gztar',
root_dir='/Users/wupeiqi/Downloads/test')
|
shutil 对压缩包的处理是调用 ZipFile 和 TarFile 两个模块来进行的,详细:
七.logging模块
用于便捷记录日志且线程安全的模块
1、单文件日志
|
1
2
3
4
5
6
7
8
9
10
11
12
13
14
|
import logging
logging.basicConfig(filename='log.log',
format='%(asctime)s
- %(name)s - %(levelname)s -%(module)s: %(message)s',
datefmt='%Y-%m-%d
%H:%M:%S %p',
level=10)
logging.debug('debug')
logging.info('info')
logging.warning('warning')
logging.error('error')
logging.critical('critical')
logging.log(10,'log')
|
日志等级:
CRITICAL = 50 FATAL = CRITICAL ERROR = 40 WARNING = 30 WARN = WARNING INFO = 20 DEBUG = 10 NOTSET = 0
注:只有【当前写等级】大于【日志等级】时,日志文件才被记录。
日志记录格式:
2、多文件日志
对于上述记录日志的功能,只能将日志记录在单文件中,如果想要设置多个日志文件,logging.basicConfig将无法完成,需要自定义文件和日志操作对象。
如上述创建的两个日志对象
- 当使用【logger1】写日志时,会将相应的内容写入 l1_1.log 和 l1_2.log 文件中
- 当使用【logger2】写日志时,会将相应的内容写入 l2_1.log 文件中