内置模块
系统内置模块就是安装 Python 解释器之后,系统给提供的模块,在需要的时候可以导入使用
序列化模块
序列化模块指的是可以把 Python 中的数据,以文本或二进制的方式进行转换,并且还能反序列化为原来的数据 为什么需要序列化:一般来说数据在程序与网络中进行传输和存储时,需要以更加方便的形式进行存储和传输,因此需要对数据进行序列化
- 文本序列化模块 json
- 二进制序列化模块 pickle
pickle 序列化
- pickle 模块提供的函数
- dumps() 序列化,返回一个序列化后的结果,可以把一个 Python 的任意对象序列化成为一个二进制
- loads() 反序列化,返回一个反序列化后的 Python 对象,可以把一个序列化后的二进制数据反序列化为 Python 对象
- dump(var,fp) 序列化,把一个数据对象进行序列化并写入到文件中
- 参数 1 var 需要序列化的数据对象
- 参数 2 fp 写入的文件对象
- load(fp) 反序列化,在一个文件中读取序列化的数据,并且完成一个反序列化
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38
| import pickle
var = 'I miss you' res1 = pickle.dumps(var) print(res1, type(res1))
var = [1, 2, 3, 4] res2 = pickle.dumps(var) print(res2)
res1 = pickle.loads(res1) res2 = pickle.loads(res2) print(res1) print(res2)
var = {'name': 'duanduan', 'age': 24, 'boyfriend': 'huanghuang'} res = pickle.dumps(var) with open('./data.txt', 'wb') as fp: fp.write(res)
with open('./data.txt', 'rb') as fp: res = fp.read() res = pickle.loads(res) print(res)
var = {'name': 'duanduan', 'age': 24, 'boyfriend': 'huanghuang'} with open('./data2.txt', 'wb') as fp: pickle.dump(var, fp)
with open('./data2.txt', 'rb') as fp: newdict = pickle.load(fp) print(newdict)
|
json 序列化
JSON(JavaScript Object Notation) 是一个轻量级数据交换格式 JSON 在 JavaScript 中是一个对象的表示方法,和 Python 中的字典的定义规则和语法都很像 在互联网中是一种通用的数据交换、数据传输、数据定义的一种数据格式
- Python 中提供 json 模块,可以把一些符合转换的 python 数据对象,转换为 json 格式的数据
- json.dumps() 将一个 Python 数据序列化为 json 格式
- json.loads() 将一个序列化后的 json 对象反序列化为 Python 格式
- json.dump() 将一个 Python 数据序列化为 json 格式并写入文件
- json.load() 将一个 json 序列化后的文件反序列化回 Python 的格式
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import json
vardict = {'name': 'duanduan', 'age': 24, 'boyfriend': 'huanghuang'} print(vardict, type(vardict))
res = json.dumps(vardict) print(res, type(res))
res = json.loads(res) print(res, type(res))
vardict = [{'name': 'duanduan', 'age': 24, 'boyfriend': 'huanghuang'}, {'name': 'duanduan', 'age': 24, 'boyfriend': 'huanghuang'}] with open('./data3.json', 'w') as fp: json.dump(vardict, fp)
with open('./data3.json', 'r') as fp: newdict = json.load(fp)
print( newdict)
|
数学模块-math
- math 模块下的一些函数
- math.ceil() 向上取整 内置函数中的 round() 是四舍五入
- math.floor() 向下取整
- math.pow() 计算数值的 n 次方,结果是浮点
- math.sqrt() 开平方运算,结果是浮点
- math.fabs() 计算绝对值,结果是浮点
- math.modf() 把一个数值拆分成小数和整数组成的元组
- math.copysign() 将第二个参数的正负号,赋值给第一个参数
- math.fsum() 对一个容器类型数据进行求和,结果是浮点数
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26
| import math
r1 = math.ceil(2.25) r2 = round(2.25) print(r1, r2)
r1 = math.floor(2.25) print(r1, r2)
res = math.pow(2, 3) print(res)
res = math.sqrt(16) print(res)
res = math.fabs(-3.14) print(res)
res = math.modf(3.14) print(res)
res = math.copysign(3.14, -9.9) print(res)
res = math.fsum([1.14, 2.35, 3.46, 4, 5]) print(res)
|
随机模块-random
导入 random 模块之后
- random.random() 返回 0-1(左闭右开) 之间的随机小数
- random.randrange(开始值,结束值[,步进值]) 随机获取指定范围内的整数
- random.randint() 随机产生指定范围内的随机整数
- random.uniform() 随机产生指定范围内的随机小数
- random.choice() 随机获取容器类型中的值
- random.shuffle() 随机打乱一个容器的值,无返回值
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
| import random
res = random.random() print(res)
res = random.randrange(5) print(res) res = random.randrange(5,10) print(res) res = random.randrange(5,10,2) print(res)
res = random.randint(2,8) print(res)
res = random.uniform(3,9) print(res)
varlist = [1,2,3,4,5,6,7] res = random.choice(varlist) print(res)
random.shuffle(varlist) print(varlist)
|
系统接口模块-os
- os.getcwd() 返回当前文件工作目录/路径
- os.chdir() 修改当前工作目录,类似于 linux 的 cd 命令
- os.listdir() 查看指定目录下所有文件 类似于 ls 命令,不指定目录时候,即当前目录下的
- os.mkdir(path,mode=0o777,dir_fd=None) 在指定位置创建一个文件夹,只能一个,若不指定位置,则在当前目录下创建一个文件夹
- path:为所要创建的文件夹名称,默认在当前工作目录下,但也可以先使用 os.chdir(),修改工作目录,可以是直接在 name 处写入要新建文件夹的位置路径带上新建文件夹名称
- mode=0o777:这个是一个系统权限,分别代表着文件所有人(user)、文件所属组(group)、其他人(other),所有数字加起来就是 777,参数必须带上 0o
- 但是这里有问题,无法真的给到权限 777,因为 python 无法传讲一个比自己这个进程权限还要高的文件
- 可以使用 linux 命令 sudo chmod -R 777 文件名
- os.makedirs(name,mode)
- name:所要创建的文件路径 这次可以递归创建啦,就算存在没有的文件夹,也可以迭代创建好
- mode:同样是权限
- os.rmdir() 删除空文件夹,不能递归调用,否则报错
- os.removedirs() 递归删除空文件夹,若叶子目录被删除掉,会尝试删除父目录,若父目录也是空的目录,则会删除,直到该目录不是空的
- 但是!! 因为 mac 系统下创建一个文件夹后会在该目录下创建一个.DS_Store 隐藏文件,因此这个文件夹不再是空文件夹了
- os.remove() 删除文件
- os.rename() 修改文件或文件夹的名字
- os.system() 可以执行系统命令比如 linux 下的 ls cd 命令等等
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19
| import os
res = os.getcwd() print(res)
os.chdir('/Users/zachary') res = os.getcwd() print(res)
res = os.listdir() print(res) res = os.listdir(path='/Users/zachary/PycharmProjects/Python教程阶段1/code') print(res)
os.mkdir(path='/Users/zachary/PycharmProjects/Python教程阶段1/code/newdir',mode=0o777)
os.makedirs('/Users/zachary/PycharmProjects/Python教程阶段1/code/newdir/a/b/c')
os.system('ls')
|
关于系统中的权限 -rw-r–r– 1 zachary staff 120 2 28 21:24 data3.txt drwxr-xr-x 5 zachary staff 160 2 28 15:22 file 第一位 d 代表这个是一个文件夹/目录,如果是-代表是一个文件 前三位代表文件所有人(user) 中间三位代表文件所属组(group) 最后三位代表其他人(other) 其中 r w x 代表不同的操作权限 r 表示可读 ==== 4 w 表示可写 ==== 2 x 表示可执行 === 1
系统接口模块-os.path
- os.path 是系统模块中的路径
- os.path.abspath() 该方法可以把一个相对路径转换成一个绝对路径
- os.path.basename() 返回路径中的最后一个部分
- os.path.dirname() 获取路径中的路径部分 返回路径中最后一个部分之前的部分
- os.path.join() 链接多个路径、组成一个新的路径
- os.path.split() 将一个路径拆分成主体和最后两个部分,以元组返回
- os.path.splitext() 将一个路径拆分成主体和后缀两部分,后缀为文件后缀
- os.path.getsize() 将返回路径所在文件的文件大小,返回值为字节
- os.path.isdir() 检测文件夹是否存在
- os.path.isfile() 检测文件是否存在
- os.path.exists() 检测文件或者路径是否存在
- os.path.samefile() 检测两个文件路径是否指向同一个目标位置(两个路径必须真实)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36
| import os
res = os.path.abspath('./') print(res)
res = os.path.basename('/Users/zachary/PycharmProjects/Python教程阶段1/code') print(res)
res = os.path.dirname('/Users/zachary/PycharmProjects/Python教程阶段1/code') print(res)
res = os.path.join('./newdir/a/', '2.jpg') print(res)
res = os.path.split('./newdir/a/b/c') print(res)
res = os.path.splitext('./newdir/a/2.jpg') print(res)
res = os.path.getsize('./83系统接口模块-os.py') print(res)
res = os.path.isdir('./newdir/a/b/c') print(res)
res = os.path.isfile('./83系统接口模块-os.py') print(res)
res = os.path.exists('./newdir/a/b/c') print(res)
a = './newdir/a/b/c' b = './newdir/a/../a/b/c' res = os.path.samefile(a, b) print(res)
|
高级文件操作模块-shutil
- shutil.copy(A,B) 将路径 A 下的文件 copy 到路径 B 下的文件,在 B 下可以重命名
- shutil.copy2(A,B) 与 copy 方法相似,但是会将原文件的信息(操作时间和权限等)一并复制
- shutil.copyfile(A,B) 功能类似上述方法,但是 过程是打开文件 A,读取 A 中内容,并且写入到新的文件 B 中
- shutil.copytree(A,B) 将整个 A 的目录结构和文件,拷贝到 B 去,B 必须不存在
- shutil.rmtree() 删除整个文件夹
- shutil.move(A,B) 将整个 A 移动到 B 去
- shutil.make_archive(A,B,C)
- A: 创建的压缩文件名称
- B: 指定压缩格式(zip、tar)
- C: 要压缩的文件或者文件夹路径
- 例子: shutil.make_archive(‘a’,’zip’,’./‘)
1 2 3 4 5 6
| shutil.copy('./data3.json','./newdir/a/data3_copy.json')
shutil.copy2('./data3.json','./newdir/a/b/data3_same.json')
res = shutil.copyfile('./data3.json','./newdir/a/b/data3_same.json') print(res)
|
压缩模块-zipfile
- zipfile.ZipFile(路径包名,模式,压缩或打包)
- 压缩的使用格式
- zipfile.ZipFile(‘data.zip’,’w’,zipfile.ZIP_DEFLATED)
- 解压缩的使用格式
- zipfile.ZipFile(‘data.zip’,’r’)
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18
| import os import zipfile
with zipfile.ZipFile('data.zip','w',zipfile.ZIP_DEFLATED) as myzip: myzip.write('data.txt') myzip.write('data2.txt') myzip.write('data3.json')
with zipfile.ZipFile('data.zip','r') as myzip: myzip.extractall('./')
with zipfile.ZipFile('data.zip','w',zipfile.ZIP_DEFLATED) as myzip: arr = os.listdir('./') for i in arr: myzip.write(i)
|
时间模块-time
- time.time() 时间戳,返回从 1970 年 1 月 1 日至此时此刻的秒数,可以加参数给定时间戳,返回对应时间
- time.ctime() 返回系统时间,字符串,可以加参数给定时间戳,返回对应时间
- time.localtime() 返回系统时间,元组,可以加参数给定时间戳,返回对应时间
- time.strftime() 格式化输出时间
- time.sleep(s) 可以暂停当前线程的执行
- time.perf_counter() 计算一个程序的执行时间
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
| import time
res = time.time() print(res)
res = time.ctime() print(res)
res = time.localtime() print( res)
t = 1640000009.7300968 res = time.ctime(t) print(res) res = time.localtime(t) print( res)
res = time.strftime('%Y-%m-%d %H:%M:%S %w') print(res)
print('start') time.sleep(5) print('over')
count = 0 start = time.perf_counter() for i in range(10000000): count += 1 end = time.perf_counter() print(end - start)
|
日历模块-calendar
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30
| import calendar
def calendar_my(year,month): res = calendar.monthrange(year, month) print(res)
week = res[0] + 1 days = res[1] print('一\t二\t三\t四\t五\t六\t日')
d = 1 count = 0
while count < week - 1: print('\t', end='') count += 1 while d <= days:
for i in range(1, 8): if d > days: print('\t', end='') else: print(d, end='\t') count += 1 d += 1 if count % 7 == 0: print('')
calendar_my(2022,3)
|
更新: 2023-12-31 17:28:38
原文: https://www.yuque.com/zacharyblock/cx2om6/zo1eq941xoagbnig
Author:
Zachary Block
Permalink:
http://blockzachary.cn/blog/2123167896/
License:
Copyright (c) 2019 CC-BY-NC-4.0 LICENSE