提示:文章写完后,目录可以自动生成,如何生成可参考右边的帮助文档
文章目录
内置函数
round:四舍五入
正常遵守四舍五入,但在n.5结构中,n为偶数则舍去,n为奇数则进一.
res1 = round(4.51) # 5
res2 = round(4.5) # 4
res3 = round(3.5) # 4
res4 = round(4.12) # 4
abs:绝对值函数
res = abs(-100) # 100
sum:计算一个序列的和
lst = [-100,20,90,35]
res = sum(lst) # 45
max min:获取一个序列里面的最大(最小)值
lst = [-100,20,90,35]
# max 获取一个序列里边的最大值
res = max(lst)
print(res)
# min 获取一个序列里边的最小值
res = min(lst)
print(res)
扩展:max min与func形成高阶函数
lst = [("Alan",81),("Cat",82),("Hurt",71),("1dao",70)]
def func(n):
return n[-1] # 按照年龄返回
"""
70 => ("1dao",70)
71 => ("Hurt",71)
81 => ("Alan",81)
82 => ("Cat",82)
"""
res = max(lst,key=func)
res = min(lst,key=func)
print(res)
dic = {"Giao":-100,"Mojo":45,"Song":-70}
def func(n):
# print(n)
return abs(dic[n])
res = max(dic,key=func)
print(res)
# 改写成lambda表达式
res = max(dic,key = lambda n : abs(dic[n]))
print(res)
pow:计算某个数值的x次方
"""pow(参数1,参数2[,参数3]) 参数3代表的是取余数"""
res = pow(2,3)
res = pow(2,3,3) # 2
res = pow(2,3,4) # 0
range:产生指定范围数据的可迭代对象
'''range(start,end,step)'''
for i in range(1,11,3):
print(i) # 1 4 7 10
for i in range(11,0,-3):
print(i) # 11 8 5 2 ...
bin / oct / hex:十进制转化成2/8/16进制
# bin 将10进制数据转化为二进制
res = bin(255)
print(res)
# oct 将10进制数据转化为八进制
res = oct(87)
print(res)
# hex 将10进制数据转化为16进制
res = hex(255)
print(res)
chr / ord:ASCII码和字符之间的相互转换
# chr 将ASCII编码转换为字符
res = chr(97)
print(res) # "A"
# ord 将字符转换为ASCII编码
res = ord("A")
print(res) # 97
eval exec:将字符串当作python代码执行
# eval 将字符串当作python代码执行
strvar = "print('深圳的天气可真的太热了,受不了')"
# strvar = "a = 90" error 不能执行
eval(strvar)
# exec 将字符串当作python代码执行(功能更强大)
"""注意点:在与用户交互的时候,慎用"""
strvar = "a = 90"
exec(strvar)
print(a)
# strvar放循环代码一样可以执行
strvar = """
for i in range(10):
print("你是大傻瓜")
"""
exec(strvar)
repr:不转义字符输出字符串
strvar = "E:\nython31_gx\day17"
print(repr(strvar))
input:接受输入字符串 (永远接受的是字符串)
name = input("你妈贵姓?")
print(name)
hash:生成哈希值
"""相同的两个数据经过哈希算法运算得出的结果一定相同"""
res1 = hash("abc")
res2 = hash("abc")
print(res1,res2)
"""
1.文件校验
2.密码加密
"""
with open("ceshi1.txt",mode="r+",encoding="utf-8") as fp:
strvar1 = fp.read()
res1 = hash(strvar)
with open("ceshi2.txt",mode="r+",encoding="utf-8") as fp:
strvar2 = fp.read()
res2 = hash(strvar)
print(res1 == res2)
补充
python中内置函数还有很多,此篇仅列出一些常用函数,详情请参考https://docs.python.org/3/library/functions.html?highlight=built#ascii
模块
模块介绍
在计算机程序的开发过程中,随着程序代码越写越多,在一个文件里代码就会越来越长,越来越不容易维护。
为了编写可维护的代码,我们把很多函数分组,分别放到不同的文件里,这样,每个文件包含的代码就相对较少,很多编程语言都采用这种组织代码的方式。在Python中,一个.py文件就可以称之为一个模块(Module)。
使用模块的好处
1.最大的好处是大大提高了代码的可维护性。其次,编写代码不必从零开始。当一个模块编写完毕,就可以被其他地方引用。我们在编写程序的时候,也经常引用其他模块,包括Python内置的模块和来自第三方的模块。
2.使用模块还可以避免函数名和变量名冲突。每个模块有独立的命名空间,因此相同名字的函数和变量完全可以分别存在不同的模块中,所以,我们自己在编写模块时,不必考虑名字会与其他模块冲突
模块的分类
模块分为三种:
1.内置标准模块(又称标准库)执行help(‘modules’)查看所有python自带模块列表
2.第三方开源模块,可通过pip install 模块名 联网安装
3.自定义模块(自己写模块自己导入调用)
模块的导入和调用
import module_a #导入
from module import xx
from module.xx.xx import xx as rename #导入后重命令
from module.xx.xx import * #导入一个模块下的所有方法,不建议使用
module_a.xxx #调用
math 数学模块
# ### 数学模块
import math
#ceil() 向上取整操作 (对比内置round)*
res = math.ceil(4.9) # 5
res = math.ceil(-3.5) # -3
print(res)
# floor() 向下取整操作 (对比内置round)*
res = math.floor(3.9) # 3
res = math.floor(-3.8) # -4
print(res)
# pow() 计算一个数值的N次方(结果为浮点数) (对比内置pow)
res = math.pow(2,3) # 8
# res = math.pow(2,3,3) error # 只有2个参数
print(res) # 结果一定是小数:8.0
# sqrt() 开平方运算(结果浮点数)*
res = math.sqrt(9)
print(res) # 结果一定是小数:3.0
# fabs() 计算一个数值的绝对值 (结果浮点数) (对比内置abs)
res = math.fabs(-99)
print(res) # 99.0
# modf() 将一个数值拆分为整数和小数两部分组成元组*
res = math.modf(13.45)
print(res) # (0.4499999999999993, 13.0)
# copysign() 将参数第二个数值的正负号拷贝给第一个 (返回一个小数)*
res = math.copysign(-13,-1)
print(res) # 返回一个小数
# fsum() 将一个容器数据中的数据进行求和运算 (结果浮点数)(对比内置sum)
lst = [1,2,3,4,6]
res = math.fsum(lst)
print(res) # 返回一个小数
#圆周率常数 pi*
res = math.pi
print(res)
random 随机模块
# ### random 随机模块
import random
# random() 获取随机0-1之间的小数(左闭右开) 0<= x <1
res = random.random()
print(res)
# randrange() 随机获取指定范围内的整数(包含开始值,不包含结束值,间隔值) **
# 一个参数
res = random.randrange(5) # 0~4
# 二个参数
res = random.randrange(2,8) # 2~7
# 三个参数
res = random.randrange(1,10,3) # 1,4,7
print(res)
# randint() 随机产生指定范围内的随机整数 (了解)
res = random.randint(3,4) # 3,4
# res = random.randint(3) error
# res = random.randint(3,7,2) error # 3 5 7
print(res)
# uniform() 获取指定范围内的随机小数(左闭右开)
res = random.uniform(1,3) # 1<=x<3 小数
# return a + (b-a) * self.random()
"""
a=3,b=1
3 + (1-3) * x = 0 => 3
3 + (1-3) * x = 1 => 1
1<x<=3
"""
res = random.uniform(3,1)
print(res)
#choice() 随机获取序列中的值(多选一)
lst = ["a","b","c","d","e"]
res = random.choice(lst)
print(res)
def mychoice(lst):
num = random.randrange(len(lst)) # 0 1 2 3 4
return lst[num]
res = mychoice(lst)
print(res)
# lambda 表达式
func = lambda lst : lst[random.randrange(len(lst))]
print(func(lst))
#sample() 随机获取序列中的值(多选多) [返回列表]
lst = ["a","b","c","d","e"]
res = random.sample(lst,1)
res = random.sample(lst,2)
print(res)
#shuffle() 随机打乱序列中的值(直接打乱原序列)
lst = ["a","b","c","d","e"]
random.shuffle(lst)
print(lst)
用random模块实现验证码的生成
def yanzhengma():
# 验证码当中含有小写字母,大写字母,数字
# 小写字母:97~122
strvar = ""
# 随机抽4次
for i in range(4):
s_char = chr(random.randrange(97,123))
# 大写字母:65~90
b_char = chr(random.randrange(65,91))
# # 0~9
num = str(random.randrange(10))
lst = [s_char,b_char,num]
strvar += random.choice(lst)
return strvar
res = yanzhengma()
print(res)
pickle 序列化\反序列化模块
1.什么是序列化和反序列化?
把不能够直接存储的数据变得可存储,这个过程叫做序列化
把文件中的数据拿出来,恢复成原来的数据类型,这个过程叫做反序列化
2.为什么要序列化?
在文件中存储的数据只能是字符串 或者是 字节流,不能是其他数据类型
如果想要存储,需要序列化.
3.Pickle的功能究竟有多强大?
pickle模块用于python特有的类型和python的数据类型间进行转换
错误的示范
with open("ceshi0727.txt",mode="w",encoding="utf-8") as fp:
fp.write(lst)
# 只有字符串可以使用encode 和 decode 转换字节流
lst.encode() error
容器类型的序列化和反序列化
# 容器类型数据可以被序列化
#dumps 把任意对象序列化成一个bytes
res = pickle.dumps(lst)
print(res)
#loads 把任意bytes反序列化成原来数据
lst = pickle.loads(res)
print(lst,type(lst))
函数的序列化和反序列化
def func():
print("我是最帅的!")
# 序列化
res = pickle.dumps(func)
print(res)
# 反序列化
func = pickle.loads(res)
func()
迭代器的序列化和反序列化
# 迭代器可以序列化
# 序列化
it = iter(range(10))
res = pickle.dumps(it)
# 反序列化
it = pickle.loads(res)
for i in it:
print(i)
dump和load(针对文件对象)
#dump 把对象序列化后写入到file-like Object(即文件对象)
lst = ["Fly","Djie","MiGod"]
with open("0728.txt",mode="wb") as fp:
# dump(数据,文件对象)
pickle.dump(lst,fp)
#load 把file-like Object(即文件对象)中的内容拿出来,反序列化成原来数据
with open("0728.txt",mode="rb") as fp:
res = pickle.load(fp)
print(res,type(res))
用dumps和loads对文件进行操作
# dumps 和 loads 对文件操作 (区分)
lst = ["Alan","Dnan","LiangC"]
res = pickle.dumps(lst)
with open("0729.txt",mode="wb") as fp:
fp.write(res)
with open("0729.txt",mode="rb") as fp:
res = fp.read()
print(res)
lst = pickle.loads(res)
print(lst , type(lst))
json 序列化和反序列化模块
关于json的定义
所有的编程语言都能够识别的数据格式叫做json,是字符串
能够通过json序列化成字符串与如下类型: (int float bool str list tuple dict None)
json,用于字符串和python数据类型间进行转换
json用法
# 1.dumps和loads是一对,可以序列化字符串
dic = {"name":"Libolun","age":81,"classroom":"python31","family":["老爸","老妈","哥哥"]}
# ensure_ascii=False 显示中文 sort_keys=True 对字典的键进行排序
res = json.dumps(dic,ensure_ascii=False,sort_keys=True)
print(res , type(res))
# 2.dump 和 load 是一对,针对于文件,把数据序列化后存储文件
dic = {"name":"Libolun","age":81,"classroom":"python31","family":["老爸","老妈","哥哥"]}
with open("ceshi0728.json",mode="w",encoding="utf-8") as fp:
json.dump(dic,fp,ensure_ascii=False)
with open("ceshi0728.json",mode="r",encoding="utf-8") as fp:
dic = json.load(fp)
print(dic, type(dic))
json和pickle的差别
JSON:
优点:跨语言(不同语言间的数据传递可用json交接)、体积小
缺点:只能支持int\str\list\tuple\dict
Pickle:
优点:专为python设计,支持python所有的数据类型
缺点:只能在python中使用,存储数据占空间大
差别
1.json序列化之后的数据类型是str,所有编程语言都识别,
但是仅限于(int float bool)(str list tuple dict None)
json不能连续load,只能一次性拿出所有数据
2.pickle序列化之后的数据类型是bytes,
所有数据类型都可转化,但仅限于python之间的存储传输.
pickle可以连续load,多套数据放到同一个文件中
3.json使用的广泛性比pickle更强.
json:可以连续dump,但是不可以连续load
json的连续dump:
"""json 可以连续dump , 但是不能连续load"""
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
with open("0728_2.json",mode="w",encoding="utf-8") as fp:
json.dump(dic1,fp)
fp.write("\n")
json.dump(dic2,fp)
fp.write("\n")
为什么json不可以连续load呢?
原因:load 在获取数据时,是一次性拿取所有内容
错误的示范:
with open("0728_2.json",mode="r",encoding="utf-8") as fp:
res = json.load(fp)
print(res)
'''这样是不可行的,load会一次性把所有数据都拿出来'''
解决办法:(for循环遍历fp文件对象,一个一个loads)
with open("0728_2.json",mode="r",encoding="utf-8") as fp:
for i in fp:
dic = json.loads(i)
print(dic,type(dic))
pickle:可以连续dump 也可以连续load 因为pickle在存储数据的时候会在末尾加上结束符
pickle的连续dump和连续load
"""pickle 可以连续dump 也可以连续load 因为pickle在存储数据的时候会在末尾加上结束符"""
import pickle
dic1 = {"a":1,"b":2}
dic2 = {"c":3,"d":4}
with open("0728_3.pkl",mode="wb") as fp:
pickle.dump(dic1,fp)
pickle.dump(dic2,fp)
with open("0728_3.pkl",mode="rb") as fp:
dic1 = pickle.load(fp)
print(dic1 , type(dic1))
dic2 = pickle.load(fp)
print(dic2 , type(dic2))
time 时间模块
# ### time 时间模块
import time
# localtime -> mktime -> ctime
# 时间元组 -> 时间戳 -> 时间字符串
time() 时间戳
# time() 获取本地时间戳 (*)
res = time.time()
print(res)
localtime() 获取本地时间元组(参数是时间戳,默认当前) (*)
# localtime() 获取本地时间元组(参数是时间戳,默认当前) (*)
res = time.localtime()
print(res)
"""
time.struct_time(
tm_year=2020,
tm_mon=7,
tm_mday=28,
tm_hour=10,
tm_min=45,
tm_sec=9,
tm_wday=1,
tm_yday=210,
tm_isdst=0
)
"""
# 指定时间戳,返回时间元组
ttp = 1595904161
res = time.localtime(ttp)
print(res)
mktime() 通过时间元组获取时间戳(参数是时间元组) (*)
# mktime() 通过时间元组获取时间戳(参数是时间元组) (*)
ttp = (2020,7,28,10,48,30,0,0,0)
res = time.mktime(ttp)
print(res) # 1595904510
ctime() 获取本地时间字符串(参数是时间戳,默认当前) (*)
# ctime() 获取本地时间字符串(参数是时间戳,默认当前) (*)
res = time.ctime() # 默认以当前时间戳获取时间字符串
print(res)
# 指定时间戳
res = time.ctime(1595904161)
print(res)
asctime() 通过时间元组获取时间字符串(参数是时间元组)(了解)
# asctime() 通过时间元组获取时间字符串(参数是时间元组)(了解)
ttp = (2020,7,28,10,54,30,6,0,0) # 不能自动识别周几.
res = time.asctime(ttp)
print(res)
# 改造办法
ttp = (2020,7,28,10,54,30,0,0,0)
res = time.mktime(ttp)
str_time = time.ctime(res)
print(str_time)
sleep() 程序睡眠等待 (*)
time.sleep(2)
print("我睡醒了")
"""
strftime => 把时间元组 -> 时间字符串
strptime => 把时间字符串 -> 时间元组
"""
strftime() 格式化时间字符串(格式化字符串,时间元祖) (*)
# strftime() 格式化时间字符串(格式化字符串,时间元祖) (*)
# 1.默认按照当前时间做格式化
res = time.strftime("%Y-%m-%d %H:%M:%S")
print(res)
# 2.指定时间元组,对时间字符串格式化
"""strftime如果在windows当中出现中文,直接报错,不能解析,linux 可以支持"""
ttp = (2000,10,1,12,12,12,0,0,0)
res = time.strftime("%Y-%m-%d %H:%M:%S" , ttp)
print(res)
perf_counter() 用于计算程序运行的时间 (了解)
# 记录开始时间
# startime = time.perf_counter()
startime = time.time()
for i in range(100000000):
pass
# 记录结束时间
# endtime = time.perf_counter()
endtime = time.time()
print(endtime - startime)
用time模块实现动态进度条
import time
# (1) 定义进度条的样式
'''%-50s让#号居左显示且占50个空位'''
print("[%-50s]" % ("#"))
print("[%-50s]" % ("###############"))
print("[%-50s]" % ("#########################"))
# (2) 让进度条动起来
strvar = ""
for i in range(50):
strvar += "#"
time.sleep(0.1)
print("\r[%-50s]" % (strvar) , end="" ) # \r的作用:将后面的字符直接拉到当前行行首
实现一个动态的进度条
# (3) 根据文件的大小,调整进度条的位置
# 假设文件的大小是 1024000
def progress(percent):
# 如果百分比超过了1,说明数据已经接受完毕;
if percent > 1:
percent = 1
# 打印对应的#号效果
strvar = "#" * int(percent * 50)
# %% => %
print("\r[%-50s] %d%%" % (strvar,int(percent * 100)) , end="" )
# 初始化接受的字节数
recv_size = 0
# 文件接受总大小
total_size = 1024000
while recv_size < total_size:
recv_size += 1024
# 模拟延迟
time.sleep(0.01)
# 计算百分比
percent = recv_size/total_size #0.001
# 调用进度条函数
progress(percent)
zipfile 压缩模块
import zipfile
# 1.压缩文件
# (1) 创建压缩包
zf = zipfile.ZipFile("1424.zip","w",zipfile.ZIP_DEFLATED)
# (2) 把文件写入到压缩包中
# write(路径,别名)
zf.write("/bin/cp","cp")
zf.write("bin/chmod","chmod")
# 可以临时创建一个文件夹在tmp在压缩包中
zf.write("/bin/df","/tmp/df")
# (3) 关闭压缩包
zf.close()
# 2.解压文件
# (1) 打开压缩包
zf = zipfile.ZipFile("1424.zip","r")
# (2) 解压文件
# 解压单个文件
zf.extract("cp","ceshi1424_2")
# 解压所有文件
zf.extractall("ceshi1424")
# (3) 关闭压缩包
zf.close()
# 3.追加文件(支持with语法)
with zipfile.ZipFile("1424.zip","a",zipfile.ZIP_DEFLATED) as zf:
zf.write("/bin/dir","dir")
# 4.查看压缩包
with zipfile.ZipFile("1424.zip","r",zipfile.ZIP_DEFLATED) as zf:
lst = zf.namelist()
print(lst)
OS 系统模块(重要)
import os
#### os模块方法 ####
# 1.system 在python中执行系统命令
os.system("ifconfig")
os.system("touch 1.txt")
# 2.popen 执行系统命令返回对象
# 可以通过read方法读出字符串,防止字符串乱码,使用popen进行操作
obj = os.popen("ifconfig")
res = obj.read()
print(res)
# 3.listdir 获取指定文件夹中的所有内容的名称列表
lst = os.listdir(".") # . 当前目录
lst = os.listdir("..") # . 上一级目录
lst = os.listdir("/home/libolun")
print(lst)
# 4.getcwd 获取当前文件所在的默认路径(单纯的路径)
res = os.getcwd()
print(res) # /mnt/hgfs/python31_gx/day19
# 路径+文件
print(__file__) # /mnt/hgfs/python31_gx/day19/1.py
# 5.chdir 修改当前文件工作的默认路径
os.chdir("/home/libolun/mywork")
os.system("mkdir ceshi100")
# 6.environ 获取或修改环境变量
print(os.environ) # 获取所有环境变量
print(os.environ["path"])
os.environ["path"] += ":/home/libolun/mywork" # 修改环境变量
os.system("libolun")
os模块属性
#### os模块属性 ####
# 1.name 获取系统标识
# linux,mac->posix windows->nt
print(os.name)
# 2.sep 获取路径分割符号
# linux,mac-> / windows-> \
print(os.sep)
# 3.linesep 获取系统的换行符号
# linux,max-> \n windows->\r\n或\n
print(repr(os.linesep))
os模块:新建和删除
#### os 负责新建和删除 ####
# 1 os.mknod 创建文件
os.mknod("1.txt")
# 2.os.remove 删除文件
os.remove("1.txt")
# 3.os.mkdir 创建文件夹
os.mkdir("ceshi100")
# 4.os.rmdir 删除文件夹
os.rmdir("ceshi100")
# 5.os.rename 对文件/文件夹重命名
os.rename("111.txt","123.py")
# 6.os.makedirs 递归创建文件夹
os.makedirs("a/b/c/d/e")
# 7.os.removedirs 递归删除文件夹(空文件夹)
os.removedirs("a/b/c/d/e")
os.path:路径模块
# 1.basename 返回文件名部分
strvar = "/home/libolun/mywork/1.py"
res = os.path.basename(strvar)
print(res) # 1.py
# 2.dirname 返回路径部分
res = os.path.dirname(strvar)
print(res) # /home/libolun/mywork
# 3.split 将路径拆分为单独的文件部分和路径部分,并组合成一个元组
tup = os.path.split(strvar)
print(tup)
# 4.join 将多个路径和文件组成新的路径
# 可以自动通过不同的系统加不同的斜杠
path1 = "ceshi1"
path2 = "libolun"
path3 = "2.py"
# pathvar = path1 + os.sep + path2 + os.sep + path3
pathvar = os.path.join(path1,path2,path3)
print(pathvar)
# 5.splitext 将路径分割为后缀和其他部分
res = os.path.splitext(strvar)
print(res) # ('/home/libolun/mywork/1','.py')
# 6.getsize 获取文件的大小
res = os.path.getsize("1.py")
# 文件夹不能计算
res = os.path.getsize("os")
print(res)
# 7.isdir 检测路径是否是一个文件夹
strvar = "/home/libolun/mywork/libolun"
res = os.path.isdir(strvar)
print(res)
# 8.isfile 检测路径是否是一个文件
strvar = "/home/libolun/mywork/libolun"
res = os.path.isfile(strvar)
print(res)
# 9.islink 检测路径是否是一个链接
strvar = "/home/libolun/mywork/libolun"
res = os.path.islink(strvar)
print(res)
# 10.getctime [windows]文件的创建时间 [linux]权限的改动时间
# 返回的是时间戳
res = os.path.getctime("1.py")
# 11.getmtime 获取文件最后一次修改时间
res = os.path.getmtime("1.py")
# 12.getatime 获取文件最后一次访问时间
res = os.path.getatime("1.py")
# 13.exists 检测指定的路径是否存在
strvar = "/home/libolun/mywork/libolun"
res = os.path.exists(strvar)
print(res)
# 14.isabs 检测一个路径是否是绝对路径
pathvar = "."
res = os.path.isabs(pathvar)
print(res)
# 15.abspath 将相对路径转化为绝对路径
pathnew = os.path.abspath(pathvar)
print(pathnew)
# 检测是否是绝对路径,如果不是,将其转化为绝对路径
if not os.path.abspath(pathvar):
pathnew = os.path.abspath(pathvar)
print(pathnew)
shutil:负责复制和移动
# 1.copyfileobj(fsrc,fdst,[,length=16*1024]) 单纯复制文件的内容
# 需要手动创建文件对象
fp1 = open("123.py",mode='r',encoding="utf-8")
fp2 = open("lianxi111.php",mode="w",encoding="utf-8")
shutil.copyfileobj(fp1,fp2)
# 2.copyfile(src,dst) 单纯的仅复制文件内容
# 在底层调用了copyfileobj
shutil.copyfile("1.php","2.js")
# 3.copymode(src,dst) 单纯的复制权限,不包括文件内容
shutil.copymode("1.php","2.js")
# 4.copystat(src,dst) 复制文件所有状态信息,不包括内容
# 状态信息:包括权限、组、用户、修改时间
shutil.copystat("1.py","2.php")
# 5.copy(src,dst) 复制文件的权限和内容
shutil.copy("1.py","2.html")
# 6.copy2(src,dst) 复制文件权限和内容,还有组,时间,用户等
shutil.copy2("1.py","2.html")
# 7.copytree(src,dst) 复制文件夹里的所有内容(递归拷贝)
shutil.copytree("lianxi001","lianxi002")
# 8.rmtree(path) 删除当前文件夹以及文件夹中的所有内容(递归删除)
shutil.rmtree("lianxi001")
# 9.move(path1,path2) 移动文件或者文件夹
shutil.move("1.php","..")
shutil.move("lianxi001","../lianxi007") # 移动并改名
tarfile:压缩模块
# 1.创建tar包
'''最小的压缩包,后缀格式为bz2'''
# 单纯的tar包
tf = tarfile.open("ceshi001.tar",'w',encoding="utf-8")
tf.add("bin/echo","echo")
tf.add("bin/ed","ed")
tf.add("bin/fuser","/tmp/fuser")
tf.close()
tf = tarfile.open("ceshi002.tar.gz",'w:gz',encoding="utf-8")
tf.add("bin/echo","echo")
tf.add("bin/ed","ed")
tf.add("bin/fuser","/tmp/fuser")
tf.close()
tf = tarfile.open("ceshi003.tar.bz2",'w:bz2',encoding="utf-8")
tf.add("bin/echo","echo")
tf.add("bin/ed","ed")
tf.add("bin/fuser","/tmp/fuser")
tf.close()
# 2.对压缩包进行解压
tf = tarfile.open("ceshi003.tar.bz2",'r',encoding="utf-8")
# 解压单个
tf.extract("echo","ceshi004")
# 解压所有
tf.extractall("ceshi005")
# 3.追加文件
# 支持with语法
# 只能为没有压缩过的tar包进行追加
with tarfile.open("ceshi001.tar",'a',encoding="utf-8") as tf:
tf.add("/bin/cp","cp")
# 4.查看压缩包中的文件
with tarfile.open("ceshi002.tar.gz",'a',encoding="utf-8") as tf:
lst = tf.getnames()
print(lst)
例题:
计算一个文件夹的大小
import os
pathvar = "/mnt/hgfs/python31_gx/day19/ceshi100"
# 递归计算文件夹的大小
def getallsize(pathvar):
size = 0
# 获取当前文件夹中所有内容
lst = os.listdir(pathvar)
# 循环列表
for i in lst:
# 拼接完整路径
pathnew = os.path.join(pathvar,i)
# 判断是否是文件或者文件夹
if os.path.isfile(pathnew):
size += os.path.getsize(pathnew)
elif os.path.isdir(pathnew):
# 如果是文件夹,继续调用函数.
size += getallsize(pathnew)
# 返回最后的结果
return size
res = getallsize(pathvar)
print(res)
如何处理tarfile不能再已经压缩过的保重追加内容的问题
import os
path = os.getcwd()
# 找到要解压的包的路径
pathvar1 = os.path.join(path,"ceshi0729_3.tar.bz2")
# 解压到哪里去
pathvar2 = os.path.join(path,"ceshi0729_3")
# (1) 先对已经压缩过的包进行解压
with tarfile.open(pathvar1,"r",encoding="utf-8") as tf:
tf.extractall(pathvar2)
# (2) 往这个解压的文件夹中添加新的文件
mybin = "cp -a /bin/fgrep " + pathvar2
# print(mybin) # cp -a /bin/fgrep /mnt/hgfs/python31_gx/day19/ceshi0729_3
os.system(mybin)
# (3) 对这个文件进行过滤筛选,重新打包压缩 (不要echo)
lst = os.listdir(pathvar2)
with tarfile.open(pathvar1,"w:bz2",encoding="utf-8") as tf:
for i in lst:
if i != "echo":
# 拼接完整路径
pathnew = os.path.join(pathvar2,i)
# add(路径,别名)
tf.add(pathnew,i)