python之强大,就是因为它其提供的模块全面,模块的知识点不仅多,而且零散---一个字!错综复杂
没办法,二八原则抓重点咯!只要抓住那些以后常用开发的方法就可以了,哪些是常用的?往下看--找答案~
模块定义
模块,用一砣代码实现了某个功能的代码集合。
类似于函数式编程和面向过程编程,函数式编程则完成一个功能,其他代码用来调用即可,提供了代码的重用性和代码间的耦合。而对于一个复杂的功能来,可能需要多个函数才能完成 (函数又可以在不同的.py文件中),n个 .py 文件组成的代码集合就称为模块。
如:os 是系统相关的模块;file是文件操作相关的模块
模块分为三种:
- 自定义模块
- 第三方模块
- 内置模块
py文件本地信息
vars()--获取字典形式的本地信息
- __doc__ py文件的注释(文件的注释写在文件的顶部)
- __package__ 返回当前.py文件所在的文件夹
from xml.etree import ElementTree
print(ElementTree.__package__) #xml.etree
- __cashed__ 缓存(pyc文件...)
- __file__ 本身自己文件的路径(os.path.dirname,os.path.join)
- if __name__ = __main__ 只有执行了主文件时,__name__ = '__main__',否则,__name__ = 模块名
- __builtins__ 和内置函数息息相关
第三方模块的下载与安装
- 软件管理工具--pip3
先安装pip3(要先安装setuptools),但是在python3默认有pip3--添加到环境变量--命令行输入:pip3 install requests
pip通常的位置是“c:\python34\Scripts”;pip install xlwt3 安装xlwt3
- 源码安装
下载源码(https://github.com/kennethreitz/requests/tarball/master)--解压--命令行进入目录--执行python setup.py install
接下来的内容讲讲python自带模块,也就是内置模块
一、sys模块
--用于和python解释器打交道
1.sys.argv 返回一个列表,第一个元素为文件路径,应用:根据用户输入,执行不同的动作,创建一个用户,启动一个服务,删除一个文件
#python创建文件夹
import sys,os
print(sys.argv) #['test.py', 'nihao']
os.mkdir(sys.argv[1]) #创建目录
2.sys. platform 返回操作系统的名称,当要求一个程序在不同平台都能实现功能,可以用if对平台进行判断,然后执行相应的程序
3.sys. exit(n) 0 是正常退出,其他都是异常退出,可以捕获
4.sys. path 按照这个路径列表去寻找模块,如果没找到就报错
- 当有模块名相同时,在不同的程序里执行模块方法,内部会按照一定顺序去路径列表找模块,先找哪个就执行哪个,这就是模块名相同时,可能功能相冲的原因
import os
import sys
tmp1 = os.path.dirname(__file__)
s = 'bin'
pt = os.path.join(tmp1,s)
sys.path.append(pt)
print(sys.path)
#['E:\\Python文件\\test文件',
'E:\\Python文件',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\python35.zip',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\DLLs', 'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35',
'C:\\Users\\Administrator\\AppData\\Local\\Programs\\Python\\Python35\\lib\\site-packages',
'E:/Python文件/test文件\\bin']
进度条
import sys
import time
for i in range(31):
sys.stdout.write('\r') #每一次清空原行
sys.stdout.write('%s%% |%s'%(int(i/30*100),int(i/30*100)*'*'))
sys.stdout.flush() #强制刷新缓冲区
time.sleep(0.3)
二、time模块和datetime模块
--用于时间相关操作
#time模块
import time
print('start to sleep...')
time.sleep(1)
print('wake up...')
print(time.time()) #1466000873.1087487--时间戳,从1970年1月1号 过了多少秒
#电脑之间校对时间
print(time.ctime()) #Wed Jun 15 22:27:53 2016--返回当前系统时间
print(time.ctime(time.time()-86400)) #Tue Jun 14 22:30:16 2016
time_obj = time.gmtime(time.time()-86400) #时间对象--utc时间
print(time_obj) #time.struct_time(tm_year=2016, tm_mon=6, tm_mday=14, tm_hour=14, tm_min=31, tm_sec=30, tm_wday=1,tm_yday=166, tm_isdst=0)
print(time_obj.tm_year) #2016
print(time.localtime(time.time()-86400)) #将时间戳转换成struct_time格式,返回本地时间--即操作系统设置时间
print(time.mktime(time.localtime())) #将一个时间对象转为时间戳
print(time.strftime('%Y-%m-%d %H:%M:%S',time.gmtime())) #将一个时间对象转换为指定的字符串格式
print(time.strptime('2016/2/25','%Y/%m/%d')) #将特定格式的字符串转为时间对象
#datetime模块
import time
import datetime
print(datetime.date.today()) #返回系统当前日期
print(datetime.date.fromtimestamp(time.time()-86400)) #将时间戳转为日期格式
current_time = datetime.datetime.now()
print(current_time) #返回当前日期时间
print(current_time.timetuple()) #转为时间对象
print(current_time.replace(2013,9,6)) #这里是替换当前时间的日期
print(datetime.date.today()+datetime.timedelta(days=5)) #datetime.timedelta --表示时间间隔,即两个时间点之间的长度
三、os模块
--提供对操作系统进行调用的接口
#os模块
#os.stat('path/filename')
import os
ret = os.stat(__file__)
print(ret,type(ret))
for i in ret:
print(i,type(i))
#========================
#os.path.dirname(path)
#os.path.join(path1[, path2[, ...]])
import os
import sys
s = 'bin'
pat = os.path.dirname(__file__)
x_pat = os.path.join(pat,s)
sys.path.append(x_pat)
print(sys.path)
#=========================
#os.path.exists(path)
path1 = os.path.dirname(__file__)
path2 = os.path.join(path1,'bin')
ret1 = os.path.exists(path1)
ret2 = os.path.exists(path2)
print(ret1,ret2)
详细列表
os.getcwd() 获取当前工作目录,即当前python脚本工作的目录路径
os.chdir(
"dirname"
) 改变当前脚本工作目录;相当于shell下cd
os.curdir 返回当前目录: (
'.'
)
os.pardir 获取当前目录的父目录字符串名:(
'..'
)
os.makedirs(
'dir1/dir2'
) 可生成多层递归目录
os.removedirs(
'dirname1'
) 若目录为空,则删除,并递归到上一级目录,如若也为空,则删除,依此类推
os.mkdir(
'dirname'
) 生成单级目录;相当于shell中mkdir dirname
os.rmdir(
'dirname'
) 删除单级空目录,若目录不为空则无法删除,报错;相当于shell中rmdir dirname
os.listdir(
'dirname'
) 列出指定目录下的所有文件和子目录,包括隐藏文件,并以列表方式打印
os.remove() 删除一个文件
os.rename(
"oldname"
,
"new"
) 重命名文件
/
目录
os.stat(
'path/filename'
) 获取文件
/
目录信息
os.sep 操作系统特定的路径分隔符,win下为
"\\",Linux下为"
/
"
os.linesep 当前平台使用的行终止符,win下为
"\t\n"
,Linux下为
"\n"
os.pathsep 用于分割文件路径的字符串
os.name 字符串指示当前使用平台。win
-
>
'nt'
; Linux
-
>
'posix'
os.system(
"bash command"
) 运行shell命令,直接显示
os.environ 获取系统环境变量
os.path.abspath(path) 返回path规范化的绝对路径
os.path.split(path) 将path分割成目录和文件名二元组返回
os.path.dirname(path) 返回path的目录。其实就是os.path.split(path)的第一个元素
os.path.basename(path) 返回path最后的文件名。如何path以/或\结尾,那么就会返回空值。即os.path.split(path)的第二个元素
os.path.exists(path) 如果path存在,返回
True
;如果path不存在,返回
False
os.path.isabs(path) 如果path是绝对路径,返回
True
os.path.isfile(path) 如果path是一个存在的文件,返回
True
。否则返回
False
os.path.isdir(path) 如果path是一个存在的目录,则返回
True
。否则返回
False
os.path.join(path1[, path2[, ...]]) 将多个路径组合后返回,第一个绝对路径之前的参数将被忽略
os.path.getatime(path) 返回path所指向的文件或者目录的最后存取时间
os.path.getmtime(path) 返回path所指向的文件或者目录的最后修改时间
四、hashlib模块
--用于加密相关的操作,3.x里代替了md5模块和sha模块,主要提供 SHA1, SHA224, SHA256, SHA384, SHA512 ,MD5 算法
#hashlib模块
#不可反解
import hashlib
#md5
m = hashlib.md5()
m.update(b"Hello")
print(m.digest())
print(m.hexdigest())
m.update(b"It's me")
print(m.digest())
print(m.hexdigest())
m.update(b"It's been a long time since last time we ...")
print(m.digest()) #2进制格式hash
print(len(m.hexdigest())) #16进制格式hash
#sha1
n = hashlib.sha1()
n.update(b'hello')
print(n.digest())
print(n.hexdigest())
以上加密算法虽然依然非常厉害,但时候存在缺陷,即:通过撞库可以反解。所以,有必要对加密算法中添加自定义key再来做加密。
import hashlib
# ######## md5 ########
hash = hashlib.md5(bytes('898oaFs09f',encoding="utf-8"))
hash.update(bytes('admin',encoding="utf-8"))
print(hash.hexdigest())
python内置还有一个 hmac 模块,它内部对我们创建 key 和 内容 进行进一步的处理然后再加密
import hmac
h = hmac.new(bytes('898oaFs09f',encoding="utf-8"))
h.update(bytes('admin',encoding="utf-8"))
print(h.hexdigest())
五、json和pickle模块
--json,用于字符串和python基础数据类型进行转换,它是多语言交互的通用序列化格式
--pickle,用于python特有的类型序列化格式
import json
import pickle
tuple1 = (11,22,3)
s = json.dumps(tuple1)
print(type(s)) #字符串
print(s) #[11, 22, 3] 自动把元组转换为列表,因为元组是python特有的数据类型
tu = json.loads(s)
print(tu)
dic = {'k1':123,'k2':'jidjfis'}
f = open('db.txt','w')
json.dump(dic,f)
f.close()
fil = open('db.txt','r')
dic2 = json.load(fil)
print(dic2)
fil.close()
dic = {'k1':123,'k2':'jidjfis'}
s = pickle.dumps(dic)
print(s,type(s)) #字节
dict2 = pickle.loads(s)
print(dict2)
with open('k.txt','wb') as f: #由于pickle是将数据转化为字节类型,所以打开文件要用字节方式打开
pickle.dump(dic,f)
with open('k.txt','rb') as f:
da = pickle.load(f)
print(da)
六、xml模块
--XML是实现不同语言或程序之间进行数据交换的协议
#xml是实现不同语言或程序之间进行数据交换的协议
from xml.etree import ElementTree as ET
#解析方式一:字符串
#打开文件读取xml内容
str_xml = open('xo.xml','r').read()
print(type(str_xml))
#将字符串解析成xml特殊对象,root代指xml文件的根节点
root = ET.XML(str_xml) #XML注意这里是大写
print(type(root))
#解析方式二:
#直接解析xml文件
tree = ET.parse('xo.xml')
#获取xml文件的根节点
root = tree.getroot()
#++++++++++++++++++++++++++++++++++++++++++++++++
#操作xml
#xml格式类型是节点嵌套节点,对于每一个节点均有以下功能,以便对当前节点进行操作
from xml.etree import ElementTree as ET
str_xml = open('xo.xml','r').read()
root = ET.XML(str_xml)
print(root.tag) #root.tag 获取根节点的标签
#遍历xml文档的第二层
for child in root:
#第二层节点的标签名称和标签属性
print(child.tag,child.attrib) #节点.attrib获取标签属性--对象为字典
#遍历xml文档的第三层
for grandson in child:
#第三层节点的标签名和内容
print(grandson.grandson.text) #grandson.text获取标签的内容,没有返回None
#遍历xml中指定的节点
from xml.etree import ElementTree as ET
tree = ET.parse('xo.xml')
root = tree.getroot()
print(root.tag)
#可以直接获取儿子也可以获取孙子
for node in root.iter('year'):
print(node.tag,node.text)
#修改节点内容
#由于修改节点时,均是在内存中进行,是不会影响文件的内容,
# 所以,如果想要修改,则需要重新将内存中的内容写到文件
#以字符串读出的方式来修改文件
from xml.etree import ElementTree as ET
str_xml = open('xo.xml','r').read()
root = ET.XML(str_xml)
print('字符串解析后是什么类型呢?——',type(root))
# for node in root.iter('year'):
#将year节点中的内容自增1000
new_year = int(node.text) + 1000
node.text = str(new_year)
#设置属性
node.set('gengxin','yes')
# 保存文件
tree = ET.ElementTree(root)
print('这什么类型:',type(tree))
tree.write('new.xml',encoding='utf-8')
#以解析文件的方式来修改文件
from xml.etree import ElementTree as et
tree = et.parse('xo.xml')
root = tree.getroot()
for node in root.iter('year'):
new_year = int(node.text) + 1000
node.text = str(new_year)
node.set('gengxin','yes')
node.set('jijfaj','luanma')
#删除属性
del node.attrib['jijfaj']
tree.write('new2.xml',encoding='utf-8')
#删除节点
from xml.etree import ElementTree as et
str_xml = open('xo.xml','r').read()
root = et.XML(str_xml)
for country in root.findall('country'): #node_name.findall返回列表
#获取每一个country节点下rank节点的内容
rank = int(country.find('rank').text)
if rank > 50:
#删除指定的country节点
root.remove(country)
tree = et.ElementTree(root)
tree.write('new3.xml',encoding='utf-8')
#==============================================
#创建xml文档
from xml.etree import ElementTree as et
#创建根节点
root = et.Element('family')
#创建节点大儿子和二儿子
da_son = et.Element('son',{'name':'er1'})
er_son = et.Element('son',{'name':'er2'})
#在大儿子中创建两个孙子
grandson1 = et.Element('grandson',{'name':'sun1'})
grandson2 = et.Element('grandson',{'name':'sun2'})
da_son.append(grandson1)
da_son.append(grandson2)
#把儿子添加到老子那-根节点
root.append(da_son)
root.append(er_son)
tree = et.ElementTree(root)
tree.write('new4.xml',encoding='utf-8',short_empty_elements=False) #默认为Ture,节点与节点间省代码
#创建方式二
from xml.etree import ElementTree as et
#创建根节点
root = et.Element('family')
#创建大儿子
son1 = root.makeelement('son',{'name':'er1'}) #这种创建方式 根节点和这儿子没有关系,还是要添加操作
#给大儿子创建孙子
sun = son1.makeelement('grandson',{'name':'sun1'})
root.append(son1)
son1.append(sun)
tree = et.ElementTree(root)
tree.write('new5.xml',encoding='utf-8')
#方法三:
from xml.etree import ElementTree as et
#创建根节点
root = et.Element('famliy')
#创建儿子
son = et.SubElement(root,'son',{'name':'er1'}) #sub 首字母是大写
#创建孙子
sun = et.SubElement(son,'sun',{'name':'sun1'})
tree = et.ElementTree(root)
tree.write('new6.xml',encoding='utf-8',xml_declaration=True)
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from xml.etree import ElementTree as ET from xml.dom import minidom def prettify(elem): """将节点转换成字符串,并添加缩进。 """ rough_string = ET.tostring(elem, 'utf-8') reparsed = minidom.parseString(rough_string) return reparsed.toprettyxml(indent="\t") # 创建根节点 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) raw_str = prettify(root) f = open("xxxoo.xml",'w',encoding='utf-8') f.write(raw_str) f.close()
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
from xml.etree import ElementTree as ET ET.register_namespace('com',"http://www.company.com") #some name # build a tree structure root = ET.Element("{http://www.company.com}STUFF") body = ET.SubElement(root, "{http://www.company.com}MORE_STUFF", attrib={"{http://www.company.com}hhh": "123"}) body.text = "STUFF EVERYWHERE!" # wrap it in an ElementTree instance, and save as XML tree = ET.ElementTree(root) tree.write("page.xml", xml_declaration=True, encoding='utf-8', method="xml")
七、configparser模块
--用于处理特定格式的文件(配置文件),其本质上是利用open来操作文件
#configparser用于处理特定格式的文件,其本质上是利用open来操作文件
import configparser
#读取文件内容
config = configparser.ConfigParser()
config.read('peizhi.txt',encoding='utf-8')
#获取所有的节点
ret = config.sections()
print(ret)
#获得指定节点下所有的键值对
ret = config.items('section1')
print(ret) #返回列表,每个键值组合成元组作为列表的元素
#获得指定节点下所有的键
ret = config.options('section2')
print(ret) #列表
#获得指定节点下指定key的值
v = config.get('section1','k2')
print(v)
#==================================
import configparser
config = configparser.ConfigParser()
config.read('peizhi.txt',encoding='utf-8')
#检查——查看文件中是否有某个节点
has_sec = config.has_section('section1')
print(has_sec) #逻辑值
#添加节点
# config.add_section('meihao') #在内存中操作
# config.write(open('peizhi.txt','w'))
#删除节点
config.remove_section('meihao') #不可以有重名的节点
config.write(open('peizhi.txt','w'))
#========================================
#对键值对的操作
import configparser
config = configparser.ConfigParser()
config.read('peizhi.txt',encoding='utf-8')
#检查——查看是否有某个键值对
has_op = config.has_option('section1','k1')
print(has_op)
#删除指定键值对
config.remove_option('section2','jia')
config.write(open('peizhi.txt','w'))
#设置
config.set('section2','jiaj','jiie')
config.write(open('peizhi.txt','w'))
八、logging模块
--用于便捷记录日志且线程安全的模块
import logging
logging.warning("user [alex] attempted wrong password more than 3 times")
logging.critical("server is down")
#输出
WARNING:root:user [alex] attempted wrong password more than 3 times
CRITICAL:root:server is down
看一下这几个日志级别分别代表什么意思
Level | When it’s used |
---|---|
DEBUG | Detailed information, typically of interest only when diagnosing problems. |
INFO | Confirmation that things are working as expected. |
WARNING | An indication that something unexpected happened, or indicative of some problem in the near future (e.g. ‘disk space low’). The software is still working as expected. |
ERROR | Due to a more serious problem, the software has not been able to perform some function. |
CRITICAL | A serious error, indicating that the program itself may be unable to continue running. |
如果想把日志写到文件里,也很简单
import logging
logging.basicConfig(filename='example.log',level=logging.INFO)
logging.debug('This message should go to the log file')
logging.info('So should this')
logging.warning('And this, too')
其中下面这句中的level=loggin.INFO意思是,把日志纪录级别设置为INFO,也就是说,只有比日志是INFO或比INFO级别更高 的日志才会被纪录到文件里,在这个例子, 第一条日志是不会被纪录的,如果希望纪录debug的日志,那把日志级别改成DEBUG就行了。
感觉上面的日志格式忘记加上时间啦,日志不知道时间怎么行呢,下面就来加上!
mport logging
logging.basicConfig(format='%(asctime)s %(message)s', datefmt='%m/%d/%Y %I:%M:%S %p')
logging.warning('is when this event was logged.')
#输出
12/12/2010 11:46:36 AM is when this event was logged.
import logging #create logger logger = logging.getLogger('TEST-LOG') logger.setLevel(logging.DEBUG) # create console handler and set level to debug ch = logging.StreamHandler() ch.setLevel(logging.DEBUG) # create file handler and set level to warning fh = logging.FileHandler("access.log") fh.setLevel(logging.WARNING) # create formatter formatter = logging.Formatter('%(asctime)s - %(name)s - %(levelname)s - %(message)s') # add formatter to ch and fh ch.setFormatter(formatter) fh.setFormatter(formatter) # add ch and fh to logger logger.addHandler(ch) logger.addHandler(fh) # 'application' code logger.debug('debug message') logger.info('info message') logger.warn('warn message') logger.error('error message') logger.critical('critical message')
九、requests模块
--发送http请求,是第三方模块
urllib等模块以供Http请求,但是,它的 API 太渣了。它是为另一个时代、另一个互联网所创建的。它需要巨量的工作,甚至包括各种方法覆盖,来完成最简单的任务
import urllib.request
f = urllib.request.urlopen('http://www.webxml.com.cn//webservices/qqOnlineWebService.asmx/qqCheckOnline?qqCode=424662508')
result = f.read().decode('utf-8')
print(result)
import requests
response = requests.get('http://www.1234567.com.cn/')
response.encoding = 'utf-8'
result = response.text
print(result)
#有参数实例
import requests
payload = {'key1': 'value1', 'key2': 'value2'}
ret = requests.get("http://httpbin.org/get", params=payload)
print(ret.url)
print(ret.text)
实例:查看火车停靠信息
import urllib
import requests
from xml.etree import ElementTree as et
#使用第三方模块requests发送http请求
r = requests.get('http://www.webxml.com.cn/WebServices/TrainTimeWebService.asmx/getDetailInfoByTrainCode?TrainCode=G666&UserID=')
result = r.text
# print(result)
#解析xml格式内容
root = et.XML(result)
for node in root.iter('TrainDetailInfo'):
print(node.find('TrainStation').text,node.find('StartTime').text,)
十、shutil模块
--高级的 文件、文件夹、压缩包 处理模块
shutil.copyfileobj(fsrc, fdst[, length])
将文件内容拷贝到另一个文件中
import shutil
shutil.copyfileobj(open('old.xml','r'), open('new.xml', 'w'))
shutil.copyfile(src, dst)
拷贝文件
shutil.copyfile('f1.log', 'f2.log')
shutil.copymode(src, dst)
仅拷贝权限。内容、组、用户均不变
shutil.copymode('f1.log', 'f2.log')
shutil.copystat(src, dst)
仅拷贝状态的信息,包括:mode bits, atime, mtime, flags
shutil.copystat('f1.log', 'f2.log')
shutil.copy(src, dst)
拷贝文件和权限
import shutil
shutil.copy('f1.log', 'f2.log')
shutil.copy2(src, dst)
拷贝文件和状态信息
import shutil
shutil.copy2('f1.log', 'f2.log')
shutil.ignore_patterns(*patterns)
shutil.copytree(src, dst, symlinks=False, ignore=None)
递归的去拷贝文件夹
import shutil
shutil.copytree('folder1', 'folder2', ignore=shutil.ignore_patterns('*.pyc', 'tmp*'))
shutil.rmtree(path[, ignore_errors[, onerror]])
递归的去删除文件
import shutil
shutil.rmtree('folder1')
shutil.move(src, dst)
递归的去移动文件,它类似mv命令,其实就是重命名。
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对象
- base_name: 压缩包的文件名,也可以是压缩包的路径。只是文件名时,则保存至当前目录,否则保存至指定路径,
#将 /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 两个模块来进行的,详细:
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import zipfile # 压缩 z = zipfile.ZipFile('laxi.zip', 'w') z.write('a.log') z.write('data.data') z.close() # 解压 z = zipfile.ZipFile('laxi.zip', 'r') z.extractall() z.close()
![](https://i-blog.csdnimg.cn/blog_migrate/8f900a89c6347c561fdf2122f13be562.gif)
![](https://i-blog.csdnimg.cn/blog_migrate/961ddebeb323a10fe0623af514929fc1.gif)
import tarfile # 压缩 tar = tarfile.open('your.tar','w') tar.add('/Users/wupeiqi/PycharmProjects/bbs2.log', arcname='bbs2.log') tar.add('/Users/wupeiqi/PycharmProjects/cmdb.log', arcname='cmdb.log') tar.close() # 解压 tar = tarfile.open('your.tar','r') tar.extractall() # 可设置解压地址 tar.close()
欢迎大家对我的博客内容提出质疑和提问!谢谢
笔者:拍省先生