python函数之内置函数 模块
abs 绝对值函数
print(abs(-1)) print(abs(100))
round 四舍五入
奇进偶不进 n.5的情况特定发生
res = round(3.87) res = round(4.51) # res = round(2.5)打印结果 2 # res = round(3.5) 打印结果4 res = round(6.51) print(res)
sum 计算一个序列得和
lst = [1,2,3,4,34] res = sum(lst) print(res) total = 0 for i in lst: total += i print(total)
max 获取一个序列里边的最大值
min 获取一个序列里边的最小值
lst = (-100,1,2,3,4,34) res = max(lst) res = min(lst) print(res)
max / min 的高阶函数的使用方式
tup = ( ("赵万里",100) , ("赵沈阳",101) , ("孟凡伟",99) ) def func(n): # print(n) # 按照年龄找到最小值元组 return n[-1] res = min(tup,key=func) print(res) res = max(tup,key=func) print(res) dic = {"赵万里":100,"赵沈阳":200,"孟凡伟":-5000} def func(n): # 如果是字典,默认传递的是键 # print(dic[n]) return abs(dic[n]) res = min(dic,key=func) res = max(dic,key=func) print(res)
pow 计算某个数值的x次方
如果是三个参数,前两个运算的结果和第三个参数取余
print(pow(2,3)) print(pow(2,3,7)) print(pow(2,3,4)) print(pow(2,3,5))
range 产生指定范围数据的可迭代对象
# 一个参数 for i in range(3): # 0 1 2 print(i) # 二个参数 for i in range(3, 8): # 3 4 5 6 7 print(i) # 三个参数 # 正向操作 for i in range(1,9,5): # 1 6 留头舍尾 print(i) # 逆向操作 for i in range(9,1,-3): # 9 6 3
bin 将10进制数据转化为二进制
print(bin(8))
oct 将10进制数据转化为八进制
print(oct(8))
hex 将10进制数据转化为16进制
print(hex(16))
chr 将ASCII编码转换为字符
print(chr(65))
ord 将字符转换为ASCII编码
print(ord("A"))
eval和exec在和第三方用户交互时候,谨慎使用
eval 将字符串当作python代码执行
strvar = "print(123)" strvar = "int(15)" print(strvar) res = eval(strvar) print(res,type(res))
# strvar = "a=3" error eval的局限性 不能创建变量
# eval(strvar)
exec 将字符串当作python代码执行(功能更强大)
strvar = "a=3" exec(strvar) print(a) strvar = """ for i in range(10): print(i) """ exec(strvar)
repr 不转义字符输出字符串
strvar = "D:\nython32_gx\tay14" res = repr(strvar) print(res)
input 接受输入字符串
res = input("输入内容") print(res , type(res))
hash 生成哈希值 文件校验
with open("ceshi1.py",mode="r",encoding="utf-8") as fp1, open("ceshi2.py",mode="r",encoding="utf-8") as fp2: res1 = hash(fp1.read()) res2 = hash(fp2.read()) if res1 == res2: print("文件校验成功") else: print("文件校验失败")
数学模块 import math
ceil() 向上取整操作 (对比内置round) ***
res = math.ceil(3.01) res = math.ceil(-3.45) print(res)
floor() 向下取整操作 (对比内置round) ***
res = math.floor(3.99) res = math.floor(-3.99) print(res)
pow() 计算一个数值的N次方(结果为浮点数) (对比内置pow)
结果为浮点数,必须是两个参数
res = math.pow(2,3) # res = math.pow(2,3,3) error print(res)
sqrt() 开平方运算(结果浮点数)
res = math.sqrt(9) print(res)
fabs() 计算一个数值的绝对值 (结果浮点数) (对比内置abs)
res = math.fabs(-1) print(res)
modf() 将一个数值拆分为整数和小数两部分组成元组
res = math.modf(3.897) print(res)
copysign() 将参数第二个数值的正负号拷贝给第一个 (返回一个小数)
res = math.copysign(-12,-9.1) print(res)
fsum() 将一个容器数据中的数据进行求和运算 (结果浮点数)(对比内置sum)
lst = [1,2,3,4] res = math.fsum(lst) print(res)
圆周率常数 pi ***
print(math.pi)
随机模块
random() 获取随机0-1之间的小数(左闭右开) 0<=x<1
res = random.random() print(res)
randrange() 随机获取指定范围内的整数(包含开始值,不包含结束值,间隔值) ***
# 一个参数 res = random.randrange(3) print(res) # 0 1 2 # 二个参数 res = random.randrange(3,6) # 3 4 5 print(res) # 三个参数 res = random.randrange(1,9,4) # 1 5 print(res) res = random.randrange(7,3,-1) # 7 6 5 4 print(res)
randint() 随机产生指定范围内的随机整数 (了解)
res = random.randint(1,3) # 1 2 3 # res = random.randint(3,5,1) error print(res)
uniform() 获取指定范围内的随机小数(左闭右开) ***
res = random.uniform(0,2) # 0<= x < 2 print(res) res = random.uniform(2,0) print(res) """ 原码解析: a = 2 , b = 0 return 2 + (0-2) * (0<=x<1) x = 0 return 2 取到 x = 1 return 0 取不到 0 < x <= 2 return a + (b-a) * self.random() """
choice() 随机获取序列中的值(多选一) **
lst = ["孙凯喜","王永飞","于朝志","须臾间","含税小"] res = random.choice(lst) print(res) def mychoice(lst): index_num = random.randrange(len(lst)) return lst[index_num] print(mychoice(lst)) # lambda 改造 mychoice = lambda lst : lst[ random.randrange(len(lst)) ] print(mychoice(lst))
sample() 随机获取序列中的值(多选多) [返回列表] **
tup = ("孙凯喜","王永飞","于朝志","须臾间","含税小") res = random.sample(tup,3) print(res)
shuffle() 随机打乱序列中的值(直接打乱原序列) **
lst = ["孙凯喜","王永飞","于朝志","须臾间","含税小"] random.shuffle(lst) print(lst)
验证码效果
# 验证码里面有大写字母 65 ~ 90 # 小写字母 97 ~ 122 # 数字 0 ~ 9 def yanzhengma(): strvar = "" for i in range(4): # 大写字母 b_c = chr(random.randrange(65,91)) # 小写字母 s_c = chr(random.randrange(97,123)) # 数字 num = str(random.randrange(10)) # 把可能出现的数据都放到列表中,让系统抽一个 lst = [b_c,s_c,num] # 抽完之后累计拼接在字符串strvar当中 strvar += random.choice(lst) # 循环四次拼接终止,返回随机码 return strvar res = yanzhengma() print(res)
pickle 序列化/反序列化模块
import pickle
序列化: 把不能够直接存储在文件中的数据变得可存储
反序列化: 把存储在文件中的数据拿出来恢复成原来的数据类型
php
serialize
unserialize
把所有的数据类型都通过pickle模块进行序列化
lst = [1,2,3] # 错误案例, 文件不能直接存储容器 , 文件只能存储字符串和字节流 """ with open("lianxi1.txt",mode="w",encoding="utf-8") as fp: fp.write(1) """
dumps 把任意对象序列化成一个bytes
res = pickle.dumps(lst) print(res , type(res))
函数可以序列化么? 可以
def func(): print("我是func函数") res = pickle.dumps(func) print(res , type(res))
迭代器可以序列化么? 可以
it = iter(range(10)) res = pickle.dumps(it) print(res , type(res))
loads 把任意bytes反序列化成原来数据
res2 = pickle.loads(res) print(res2 , type(res2))
dump 把对象序列化后写入到file-like Object(即文件对象)
lst = [1,2,3] with open("lianxi1.txt",mode="wb") as fp: pickle.dump(lst,fp)
load 把file-like Object(即文件对象)中的内容拿出来,反序列化成原来数据
with open("lianxi1.txt",mode="rb") as fp: res2 = pickle.load(fp) print(res2 , type(res2))
dumps 和 loads 对文件进行写入读取字节流操作
# 写入字节流 with open("lianxi2.txt",mode="wb+") as fp: res1 = pickle.dumps(lst) fp.write(res1) # 读取字节流 with open("lianxi2.txt",mode="rb+") as fp: bytes_str = fp.read() res = pickle.loads(bytes_str) print(res , type(res2))
json 序列化/反序列化模块
json格式的数据,所有的编程语言都能识别,本身是字符串
类型有要求: int float bool str list tuple dict None
json 主要应用于传输数据 , 序列化成字符串
pickle 主要应用于存储数据 , 序列化成二进制字节流
json 基本用法
json => dumps 和 loads
ensure_ascii=False 显示中文 sort_keys=True 按键排序
dic = {"name":"梁新宇","sex":"野味","age":22,"family":["爸爸","妈妈","姐姐"]} res = json.dumps(dic,ensure_ascii=False,sort_keys=True) print(res , type(res)) dic = json.loads(res) print(dic , type(dic))
json => dump 和 load
with open("lianxi3.json",mode="w",encoding="utf-8") as fp: json.dump(dic,fp,ensure_ascii=False) with open("lianxi3.json",mode="r",encoding="utf-8") as fp: dic = json.load(fp) print(dic , type(dic))
json 和 pickle 之间的区别
1.json
json 连续dump数据 , 但是不能连续load数据 , 是一次性获取所有内容进行反序列化.
dic1 = {"a":1,"b":2} dic2 = {"c":3,"d":4} with open("lianxi4.json",mode="w",encoding="utf-8") as fp: json.dump(dic1,fp) fp.write("\n") json.dump(dic2,fp) fp.write("\n") # 不能连续load,是一次性获取所有数据 , error """ with open("lianxi4.json",mode="r",encoding="utf-8") as fp: dic = json.load(fp) """ # 解决办法 loads(分开读取) with open("lianxi4.json",mode="r",encoding="utf-8") as fp: for line in fp: dic = json.loads(line) print(dic,type(dic))
2.pickle
""" with open("lianxi5.pkl",mode="rb") as fp: dic1 = pickle.load(fp) dic2 = pickle.load(fp) print(dic1) print(dic2) """ # 方法二 (扩展) """try .. except .. 把又可能报错的代码放到try代码块中,如果出现异常执行except分支,来抑制报错""" # 一次性拿出所有load出来的文件数据 try: with open("lianxi5.pkl",mode="rb") as fp: while True: dic = pickle.load(fp) print(dic) except: pass
json 和 pickle 两个模块的区别:
(1)json序列化之后的数据类型是str,所有编程语言都识别,
但是仅限于(int float bool)(str list tuple dict None)
json不能连续load,只能一次性拿出所有数据
(2)pickle序列化之后的数据类型是bytes,用于数据存储
所有数据类型都可转化,但仅限于python之间的存储传输.
pickle可以连续load,多套数据放到同一个文件中
time 时间模块
time() 获取本地时间戳
res = time.time() print(res)
localtime <=> mktime => ctime
localtime() 获取本地时间元组 (参数是时间戳,默认当前)
# 默认当前时间元组 ttp = time.localtime() print(ttp) # 指定具体的时间戳 ttp = time.localtime(1601360000) print(ttp)
mktime() 通过时间元组获取时间戳 (参数是时间元组)
res1 = time.mktime(ttp) print(res1)
ctime() 获取本地时间字符串(参数是时间戳,默认当前)
# 默认当前时间戳 res = time.ctime() print(res) # 指定具体的时间戳 res = time.ctime(res1) print(res)
asctime() 通过时间元组获取时间字符串(参数是时间元组) (了解)
只能通过手动的形式来调星期
ttp = (2020,9,29,16,48,30,0,0,0) res = time.asctime(ttp) print(res)
mktime 配合 ctime来取代asctime (推荐)
自动识别当前是周几
res = time.mktime(ttp) strvar = time.ctime(res) print(strvar)
sleep() 程序睡眠等待
time.sleep(10) print("我睡醒了")
strftime() 格式化时间字符串(格式化字符串,时间元祖)
linux支持中文 windows不支持
strvar = time.strftime("%Y-%m-%d %H:%M:%S") strvar = time.strftime("%Y-%m-%d %H:%M:%S 是杜兰特的死神的生日") print(strvar) strvar = time.strftime("%Y-%m-%d %H:%M:%S",(2020,10,31,10,10,10,0,0,0)) print(strvar)
strptime() 将时间字符串通过指定格式提取到时间元组中(时间字符串,格式化字符串)
注意:替换时间格式化标签时,必须严丝合缝.不能随便加空格或特殊字符
ttp = time.strptime("2020年的9月29号是死神杜兰特的生日,晚上20点30分40秒准备轰趴派队","%Y年的%m月%d号是死神杜兰特的生日,晚上%H点%M分%S秒准备轰趴派队") print(ttp)
strftime : 把时间元组 => 字符串
strptime : 把字符串 => 时间元组
perf_counter() 用于计算程序运行的时间 (了解)
# startime = time.perf_counter() startime = time.time() for i in range(10000000): pass # endtime = time.perf_counter() endtime = time.time() print("中间用时:",endtime-startime)
zipfile 压缩模块
import zipfile
(1) 压缩文件
zipfile.ZIP_DEFLATED 压缩减少空间
# 创建压缩包 zf = zipfile.ZipFile("ceshi111.zip","w", zipfile.ZIP_DEFLATED) # 写入文件 '''write(路径,别名)''' zf.write("/bin/bash","bash") zf.write("/bin/bunzip2","bunzip2") zf.write("/bin/cat","tmp/cat") # 关闭文件 zf.close()
(2) 解压文件
zf = zipfile.ZipFile("ceshi111.zip","r") # 解压单个文件 """extract(文件,路径)""" # zf.extract("bash","ceshi111") # 解压所有文件 zf.extractall("ceshi222") zf.close()
(3) 追加文件
zf = zipfile.ZipFile("ceshi111.zip","a", zipfile.ZIP_DEFLATED) zf.write("/bin/chmod","chmod") zf.close() # 用with来简化操作 with zipfile.ZipFile("ceshi111.zip","a", zipfile.ZIP_DEFLATED) as zf: zf.write("/bin/chmod","chmod123456")
(4) 查看文件
with zipfile.ZipFile("ceshi111.zip","r") as zf: lst = zf.namelist() print(lst)
进度条
import time """ [###################################] 100% [############## ] 40% [############################# ] 80% """ # (1) 定义进度条样式 """ print("[%-50s]" % ("#")) print("[%-50s]" % ("######################")) print("[%-50s]" % ("##############################################")) """ # (2) 让进度条动起来 """ strvar = "" for i in range(50): time.sleep(0.1) strvar += "#" print("\r[%-50s]" % (strvar) , end="") """ # (3) 加上百分比 # 显示进度条 def myprocess(percent): if percent > 1: percent = 1 # 打印对应的#号数量 * "#" => 字符串#号效果 strvar = int(percent * 50) * "#" # 进行打印 %% => % print("\r[%-50s] %d%%" % (strvar , percent * 100) , end="") # 接受数据 recv_size = 0 total_size = 1000 while recv_size < total_size: time.sleep(0.01) recv_size += 10 percent = recv_size/total_size # 0.5 myprocess(percent)
os 模块
import os
system() 在python中执行系统命令
os.system("ifconfig") # linux # os.system("ipconfig") windows # os.system("rm -rf ceshi.txt")
popen() 执行系统命令返回对象,通过read方法读出字符串
obj = os.popen("ipconfig") print(obj) print(obj.read())
listdir() 获取指定文件夹中所有内容的名称列表 ***
lst = os.listdir() print(lst)
getcwd() 获取当前文件所在的默认路径 ***
# 路径 res = os.getcwd() print(res) # 路径 + 文件名 *** print(__file__)
chdir() 修改当前文件工作的默认路径
os.chdir("/home/wangwen/mywork") os.system("touch 2.txt")
environ 获取或修改环境变量
""" [windows] (1)右键qq属性找路径 (2)右键我的电脑属性->高级系统设置->环境变量->path 打开环境变量添加对应路径 (3)cmd => QQScLauncher [linux] (1)在家目录中创建个文件夹,里面创建个文件wangwen,写入ifconfig (2)增加wangwen的可执行权限 chmod 777 wangwen 测试一下 sudo ./wangwen (3)添加环境变量在os.environ["PATH"] 中拼接wangwen所有的绝对路径 (4)os.system("wangwen") 总结: 环境变量path的好处是,让系统自动的找到该命令的实际路径进行执行; """ print(os.environ["PATH"]) """ environ( { 一堆路径} ) """ os.environ["PATH"] += ":/home/wangwen/mywork" os.system("wangwen")
--os 模块属性
name 获取系统标识 linux,mac ->posix windows -> nt
print(os.name)
sep 获取路径分割符号 linux,mac -> / window-> \ ***
print(os.sep)
linesep 获取系统的换行符号 linux,mac -> \n window->\r\n 或 \n
print(repr(os.linesep))
os 模块 (文件操作) 新建/删除/
import os os.chdir("/路径/路径/路径")
-- os模块具有 新建/删除/
os.mknod 创建文件
os.mknod("1.txt")
os.remove 删除文件
os.remove("1.txt")
os.mkdir 创建目录(文件夹)
os.mkdir("ceshi111")
os.rmdir 删除目录(文件夹)
os.rmdir("ceshi111")
os.rename 对文件,目录重命名
os.rename("2.txt","3.txt")
os.makedirs 递归创建文件夹
os.makedirs("a/b/c/d/e/f")
os.removedirs 递归删除文件夹(空文件夹)
os.removedirs("a/b/c/d/e/f")
shutil模块 复制/移动/
import shutil
copyfileobj(fsrc, fdst[, length=16*1024]) 复制文件 (length的单位是字符(表达一次读多少字符/字节))
fp_src = open("3.txt",mode="r",encoding="utf-8") fp_dst = open("4.txt",mode="w",encoding="utf-8") shutil.copyfileobj(fp_src,fp_dst)
copyfile(src,dst) #单纯的仅复制文件内容 , 底层调用了 copyfileobj
shutil.copyfile("4.txt","5.txt")
copymode(src,dst) #单纯的仅复制文件权限 , 不包括内容 (虚拟机共享目录都是默认777)
注意: 要先有两个文件才可以,不会默认创建
copystat(src,dst) #复制所有状态信息,包括权限,组,用户,修改时间等,不包括内容
shutil.copystat("4.txt","5.txt")
copy(src,dst) #复制文件权限和内容
shutil.copy("5.txt","6.py")
copy2(src,dst) #复制文件权限和内容,还包括权限,组,用户,时间等
shutil.copy2("5.txt","7.py")
copytree(src,dst) #拷贝文件夹里所有内容(递归拷贝)
shutil.copytree("lianxi","lianxi2")
rmtree(path) #删除当前文件夹及其中所有内容(递归删除)
shutil.rmtree("lianxi2")
move(path1,paht2) #移动文件或者文件夹
# shutil.move("7.py","lianxi/888.php") shutil.move("7.py","/888.php")
os.path 路径模块
import os
pathvar = "/home/wangwen/mywork/ceshi.py" pathvar = __file__
basename() 返回文件名部分
res = os.path.basename(pathvar) print(res)
dirname() 返回路径部分
res = os.path.dirname(pathvar) print(res)
split() 将路径拆分成单独的文件部分和路径部分 组合成一个元组
print(os.path.split(__file__))
join() 将多个路径和文件组成新的路径 可以自动通过不同的系统加不同的斜杠 linux / windows\ ***
path1 = "home" path2 = "wangwen" path3 = "mywork" pathvar = path1 + os.sep + path2 + os.sep + path3 print(pathvar) # 用join改造 path_new = os.path.join(path1,path2,path3) print(path_new)
splitext() 将路径分割为后缀和其他部分 (了解)
pathvar = "/home/wangwen/mywork/ceshi.py" print( os.path.splitext(pathvar) ) print( pathvar.split(".")[-1] )
getsize() 获取文件的大小 ***
# pathvar = os.path.dirname(__file__) # 方法一 pathvar = os.getcwd() # 方法二 path_new = os.path.join(pathvar,"2.py") print(path_new)
计算文件大小
res = os.path.getsize(path_new) print(pathvar) res = os.path.getsize("/mnt/hgfs/python32_gx/day14") print(res)
isdir() 检测路径是否是一个文件夹 ***
res = os.path.isdir("/mnt/hgfs/python32_gx/day14") print(res)
isfile() 检测路径是否是一个文件 ***
res = os.path.isfile("/mnt/hgfs/python32_gx/day16/1.py") print(res)
islink() 检测路径数否是一个链接
res = os.path.islink("/home/wangwen/mywork/1122.py") print(res)
getctime() [windows]文件的创建时间,[linux]权限的改动时间(返回时间戳)
import time
import time res = os.path.getctime("/home/wangwen/mywork/4.txt")
getmtime() 获取文件最后一次修改时间(返回时间戳)
res = os.path.getmtime("/home/wangwen/mywork/4.txt")
getatime() 获取文件最后一次访问时间(返回时间戳)
res = os.path.getatime("/home/wangwen/mywork/4.txt") print(res) print(time.ctime(res))
exists() 检测指定的路径是否存在 ***
res = os.path.exists("/home/wangwen/mywork/4.txt") # res = os.path.exists("4.txt")
isabs() 检测一个路径是否是绝对路径
res = os.path.isabs("2.py") print(res)
abspath() 将相对路径转化为绝对路径
res = os.path.abspath("2.py") print(res) pathvar = "2.py" if not os.path.isabs(pathvar): abs_path = os.path.abspath("2.py") print(abs_path)
tarfile 压缩模块
import tarfile
(1) 压缩文件
1.只是单纯的打包.
# 创建压缩包 tf = tarfile.open("ceshi0930_0.tar","w",encoding="utf-8") # 写入文件 """add(路径,别名)""" tf.add("/bin/chown","chown") tf.add("/bin/cp","cp") tf.add("/bin/dash","tmp/dash") # 关闭文件 tf.close() # 378880
2.使用gz算法压缩
tf = tarfile.open("ceshi0930_1.tar.gz","w:gz",encoding="utf-8") # 写入文件 """add(路径,别名)""" tf.add("/bin/chown","chown") tf.add("/bin/cp","cp") tf.add("/bin/dash","tmp/dash") # 关闭文件 tf.close() # 180413
3.使用bz2算法压缩
tf = tarfile.open("ceshi0930_2.tar.bz2","w:bz2",encoding="utf-8") # 写入文件 """add(路径,别名)""" tf.add("/bin/chown","chown") tf.add("/bin/cp","cp") tf.add("/bin/dash","tmp/dash") # 关闭文件 tf.close() # 163261
(2) 解压文件
tf = tarfile.open("ceshi0930_1.tar.gz","r",encoding="utf-8") """ extract(文件,路径) 解压单个文件""" tf.extract("chown","ceshi0930_1") """ extract(路径) 解压所有文件""" tf.extractall("ceshi0930_1_2") tf.close()
(3) 追加文件
对已经压缩过的包无法进行追加文件,只能是没有压缩过的包进行追加文件
tf = tarfile.open("ceshi0930_0.tar","a",encoding="utf-8") tf.add("/bin/mkdir","mkdir") tf.close() # 使用with进行改造 with tarfile.open("ceshi0930_0.tar","a",encoding="utf-8") as tf: tf.add("/bin/mkdir","mkdir234")
(4) 查看文件
with tarfile.open("ceshi0930_0.tar","r",encoding="utf-8") as tf: lst = tf.getnames() print(lst)
追加文件到压缩包中在压缩
import os,shutil """ 1.把已经压缩的包进行解压 2.把要追加的内容放进去 3.过滤文件重新压缩 """ # 记录压缩包所在的绝对路径 pathvar1 = os.path.abspath("ceshi0930_2.tar.bz2") # 要解压到哪个文件夹中(绝对路径) pathvar2 = os.path.join( os.getcwd() , "ceshi0930_2" ) print(pathvar1)# /mnt/hgfs/python32_gx/day16/ceshi0930_2.tar.bz2 print(pathvar2)# /mnt/hgfs/python32_gx/day16/ceshi0930_2 # 1.把已经压缩的包进行解压 with tarfile.open(pathvar1,"r",encoding="utf-8") as tf: tf.extractall(pathvar2) # 2.把要追加的内容放进去 shutil.copy("/bin/echo" , pathvar2) # 3.过滤文件重新压缩 # 查看文件夹当中有什么文件 lst = os.listdir(pathvar2) print(lst) # ['chown', 'cp', 'echo', 'tmp'] with tarfile.open(pathvar1,"w:bz2",encoding="utf-8") as tf: for i in lst: if i != "chown": # 拼凑成完整的绝对路径 abs_path = os.path.join(pathvar2,i) # 剩下的都要压缩 """add(路径,别名)""" tf.add(abs_path,i) """ /mnt/hgfs/python32_gx/day16/ceshi0930_2/chown /mnt/hgfs/python32_gx/day16/ceshi0930_2/cp /mnt/hgfs/python32_gx/day16/ceshi0930_2/echo tf.add("/bin/chown","chown") """