Python Note -- Day 10. 内置模块

本文介绍了Python内置模块的多个方面,包括序列化模块pickle和json,数学模块Math,随机模块random,操作系统接口模块,高级文件操作模块shutil,压缩模块zipfile,时间模块time,日历模块calendar以及HTTP请求库requests。通过这些模块,开发者可以进行数据序列化、数学计算、文件操作、网络请求等多种任务。
摘要由CSDN通过智能技术生成

16 内置模块

安装Python解释器后,系统提供的模块,在需要时可以导入使用

通过pickle模块的序列化操作我们能够将程序中运行的对象信息保存到文件中去,永久存储。

通过pickle模块的反序列化操作,我们能够从文件中创建上一次程序保存的对象。

16.1 序列化模块 pickle

序列化是指可以把python中的数据,以文本或二进制的方式进行转换,并且还能反序列化为原来数据
import pickle

import pickle
'''
为什么要序列化?
数据在程序与网络中进行传输和存储时,需要以更加方便的形式进行操作,因此需要对数据进行序列化

pickle模块提供的函数
    dumps()  序列化,可以把一个python的任意对象序列化为一个二进制,返回一个序列化后的二进制数据
    loads()  反序列化,把一个序列化后的二进制数据反序列化为python对象
    
    dump()  序列化,把一个数据对象序列化并写入到文件中
        obj, 需要序列化的数据对象
        file,写入的文件对象
        pickle.dump(obj,file)
    load()  反序列化,从文件中读取序列化的数据,并且完成一个反序列化
        file,读取的文件对象
        pickle.load(file)
'''

16.1.1 基本的序列化和反序列化操作

import pickle
vars = 'i love u'
vars = [1,2,3,'5','tt']   # b'\x80\x03]q\x00(K\x01K\x02K\x03X\x01\x00\x00\x005q\x01X\x02\x00\x00\x00ttq\x02e.' <class 'bytes'>
vars = {'a':1,'bb':'4'}   # b'\x80\x03}q\x00(X\x01\x00\x00\x00aq\x01K\x01X\x02\x00\x00\x00bbq\x02X\x01\x00\x00\x004q\x03u.' <class 'bytes'>
# pickle.dumps()序列化
res = pickle.dumps(vars)
# pickle.loads()反序列化
res = pickle.loads(res)
print(res,type(res))
  • 如何把一个python数据进行序列化后写入文件中,并且再次读取出来
# 1.普通方法 使用 dumps() loads()
# 定义数据
vars = {'a':1,'bb':'4'}
# 进行序列化
res = pickle.dumps(vars)
# 写入文件
with open('./2.txt','wb') as fp:
    fp.write(res)
print(res)
# 反序列化,打开文件进行读取
with open('./2.txt','rb') as fp:
    res = fp.read()
# 进行反序列化
ress = pickle.loads(res)
print(ress)

# 2. 使用pickle模块提供的load(),dump()
vars = {'a':1,'bb':'4','c':2}
with open('./2.txt','wb') as fp:
    # 在此处调用pickle
    pickle.dump(vars,fp)
with open('./2.txt','rb') as fp:
    new = pickle.load(fp)
print(new)

16.2 json 序列化

JavaScript Object Notation
——受JavaScript的对象字面量语法启发的轻量级数据交换格式
——在js语言中是一个对象的表示方法,和python中字典的定义规则和语法都很像
——在互联网中又是一种通用的数据交换、数据传输、数据定义的一种数据格式
import json

python中提供的json模块,可以把一些符合转换的python数据对象,转为json格式的数据
   json.dumps()
   json.loads()
   
   json.dump()
   json.load()
import json
vars = {'a':1,'bb':'4','c':2}
vars = [1,2,'a','tt']
vars = 'nicee'
vars = 555
# vars = {1,4,'ss'}   # TypeError: Object of type set is not JSON serializable
print(vars,type(vars))
# 使用json模块的 dumps 进行json格式转换
res = json.dumps(vars)   # {"a": 1, "bb": "4", "c": 2} <class 'str'>
print(res,type(res))
# 使用json的 loads 进行反转换
ree = json.loads(res)
print(ree,type(ree))

vars = [{'a':1,'bb':'4','c':2},{'n':'ll','ag':8}]
with open('./2.txt','w') as fp:
    json.dump(vars,fp)
with open('./2.txt','r') as fp:
    res = json.load(fp)
print(res)

检索指定路径下后缀是 py 的所有文件:

获取文件后缀:

用户输入"xxx.txt"类文档文件名

用户输入被替换的"待替换字"

用户输入替换目标"新的字"

用户判断是否全部替换 yes/no

 文本中替换字符串:cainiao

16.3 数学模块 Math

16.3.1 math函数

import math

  • math.ceil() 向上取整 , 内置函数 round() 四舍五入 类似
import math
res = math.ceil(1.25)
re1 = round(2.5)    # 内置函数 round() 类似
print(res,re1)  # 2 2
  • math.floor() 向下取整
import math
res = math.floor(1.25)
  • math.pow() 计算N次方,结果是浮点
r1 = pow(3,4)
import math
r2 = math.pow(3,4)
print(r1,r2)  # 81 81.0
  • math.sqrt() 开平方运算,结果是浮点
import math
r2 = math.sqrt(6561)
print(r2)  # 81.0
  • math.fabs() 计算绝对值,结果是浮点
  • math.modf() 把数值拆分成小数和整数组成的元组,结果是浮点
import math
r2 = math.modf(-88.23)
r1 = math.modf(4)  # (0.0, 4.0)
print(r1,r2)  # (-0.23000000000000398, -88.0)
  • math.copysign(x,y) 把第二个参数的正负符号传递给第一个参数,结果是浮点
import math
r1 = math.copysign(-3,7)
print(r1)  # -3.0
  • math.fsum() 对一个容器类型数据的元素进行求和运算,结果浮点
import math
r1 = math.fsum({3,7})
  • math.factorial() 阶乘
import math
r1 = math.factorial(7)
print(r1)   # 5040
  • math.trunc(x)  返回 x 截断整数的部分,即返回整数部分,忽略小数部分。

不会将数字向上/向下舍入到最接近的整数,而只是删除小数。

import math
print(math.trunc(8.32))
print(math.trunc(-99.29))

16.3.2 常量

  • math.pi 精确到可用精度
import math
r1 = math.pi
print(r1)   # 3.141592653589793

from math import pi

from math import pi
print(pi)

16.4 随机模块 random

import random

  • random.random() 返回[0-1)之间的随机小数
  • random.randrange([start],end,[step]) 随机获取指定范围内的整数
    左闭右开
  • random.randint(start,end) 随机产生指定范围内的整数
    都是闭,必须要两个参数
  • random.uniform(start,end) 获取指定范围的随机小数
  • random.choice() 随机获取容器类型中的值,集合不可以
import random
res = random.randrange(5,10)
res = random.randrange(10)
res = random.randrange(5,10,2)
r1 = random.randint(5,10)
r3 = random.uniform(5,10)
r4 = random.choice('123ab')
print(res,r1,r3,r4)
  • random.shuffle() 随机打乱当前 列表 中的值,返回None
import random
r = [1,2,3,'a',4]
res = random.shuffle(r)
print(res) # None
print(r)
  • random.sample(population,k)
    返回从总体序列或集合中选择的唯一元素的k长度列表,用于无重复的随机抽样
random.randrange(3) 等价于 random.choice(range(0, 3))。
函数 random.randint(4) 返回?

16.5 操作系统接口模块

16.5.1 os模块

  • os.getcwd()
    返回当前的工作目录,注意获取的不是当前脚本的目录,而是执行
    ,从哪个位置执行的脚本
# 如果在当前目录执行这个脚本文件,那么getcwd获取的就是当前的文件目录
# 如果把执行的目录切换到其他位置,执行当前脚本,获取的就是执行这个脚本时的目录
import os
res = os.getcwd()
print(res)
  • os.chdir()
    修改当前的工作目录
import os
# 修改
res = os.chdir('E:\PycharmProjects')
res = os.chdir('E:/book')
# 修改工作目录后,再去获取当前工作目录
res = os.getcwd()
print(res)
  • os.listdir(path='.')
    获取当前或指定目录中的所有项(文件,隐藏文件,文件夹),组成 列表
import os
# 不指定目录,默认为当前工作目录
res = os.listdir()   # 相当于 windows中的 dir
res = os.listdir('E:/TV')  # 必须是 /
print(res)  # ['fix', 'learn', 'open course', 'TED', '英剧_神探夏洛克', '黑色孤儿']
  • os.mkdir(path,mode=0o777)
    创建一个文件夹,不能递归创建
    mode,权限仅Linux
import os
# 不指定路径,默认在当前工作目录创建文件夹
res = os.mkdir('test')
res = os.mkdir('./test/test') # 指定路径
print(res)   # None
  • os.makedirs() 可以递归创建文件夹
  • os.rmdir() 删除 空 文件夹
import os
# 不指定路径,默认在当前工作目录路径查找并删除指定的一个文件夹
res = os.rmdir('test/aa')
res = os.rmdir('../one/two/three')
print(res)   # None
  • os.removedirs() 递归删除 空 文件夹
    先删除子目录,若父目录为空则继续删除
import os
res = os.removedirs('test/aa')
res = os.removedirs('../one/two/three')
print(res)   # None

Mac系统中,若连续创建空文件夹后,使用过某个文件夹,就会默认创建一个隐藏文件,这时文件夹就不是空文件夹了

  • os.remove() 删除文件
  • os.rename() 修改文件或文件夹的名字
    res = os.rename('test/aa','test/AA')
  • os.system() 执行操作系统中的命令
    如windows系统中的命令可以在其中执行
import os
os.system('cd')  # E:\PycharmProjects\pythonProject

16.5.2 os.path 路径模块

  • os.path.abspath() 将相对路径转为绝对路径 -very important- 重要
import os
res = os.path.abspath('./')
print(res)   # E:\PycharmProjects\pythonProject
  • os.path.basename() 获取路径的主体部分
    res = os.path.basename('e:test/test/aa') # aa
  • os.path.dirname() 获取路径的路径部分
    res = os.path.dirname('e:test/test/aa') # e:test/test
  • os.path.join() 连接多个路径,组成一个新路径
# 文件路径做拼接的时候,使用
import os
res = os.path.join('./test/test','1.txt')    # ./test/test\1.txt
res = os.path.join('./test/test/','1.txt')   # ./test/test/1.txt
res = os.path.join('./test/test','/1.txt')   # /1.txt
res = os.path.join('./test/test','./1.txt')  # ./test/test\./1.txt
  • os.path.split() 拆分路径,分为路径和主体部分
    res = os.path.split('./test/test/aa') # ('./test/test', 'aa')
  • os.path.splitext() 拆分路径,可以拆分文件后缀名
import os
res = os.path.splitext('./test/test/aa/1.py')  # ('./test/test/aa/1', '.py')
res = os.path.splitext('./test/test/aa/1')  # ('./test/test/aa/1', '')
  • os.path.getsize() 获取文件的大小,字节数
import os
res = os.path.getsize('./第一天.md')
print(res) # 6074
  • os.path.isdir() 检测是否是一个文件夹,是否存在
    res = os.path.isdir('./第一天.md')
  • os.path.isfile() 检测是否是一个文件,是否存在 重要*
    res = os.path.isfile('./test/1.txt')
  • os.path.exists() 检测路径是否存在
    res = os.path.exists('./test/1.txt')
  • os.path.samefile()
    检测两个路径是否同时指向了一个目标位置(两个路径必须真实)
import os
a = './test/AA/test.txt'
b = './test/../test/AA/test.txt'
res = os.path.samefile(a,b)
print(res) # True

16.6 高级文件操作模块 shutil

shell utility

  • shutil.copy() 把一个文件拷贝到指定目录下
import shutil
shutil.copy('test/AA/test.txt','test')
  • shutil.copy2() 和copy一样,拷贝文件到指定目录,保留原文件的信息(操作时间和权限)
  • shutil.copyfile() 拷贝文件内容,写入到新文件中
  • shutil.copytree() 把整个目录结构和文件复制到新建文件夹中,目标目录原先不存在
import shutil
shutil.copytree('test','test2/test')  # test2 和 test 原先都不存在
  • shutil.rmtree(path,ignore_error = False,οnerrοr=None)
    删除整个目录和文件
    删除整个目录树,路径必须指向目录,(但不能指向目录的符号链接)。若ignore_error为true,则删除失败导致的错误将被忽略;若False或忽略,则通过调用 onerror指定的处理程序来处理此类错误;如果省略,则引发异常。
    若提供了onerror,则他必须是可调用的,可接受三个参数:function,path和excinfo。
    第一个参数function是引发异常的函数,这取决于平台和实现。path,是传递给function的路径名。excinfo,是返回的异常信息sys.exc_info()。由onerror引发的异常不会被捕获。
import shutil
shutil.rmtree('test2/test')
  • shutil.move() 移动文件或文件夹到指定目录,也可以用于修改文件夹或文件的名称
    shutil.move('test2/test/AA','test2/test/aa')

16.7 压缩模块 zipfile

  • zipfile.ZipFile() 压缩文件
import zipfile
with zipfile.ZipFile('spam.zip','w') as myzip:
    myzip.write('1.txt')
    myzip.write('2.txt')

zipfile.ZIP_DEFLATED 常用压缩方法的数字常数

import os,zipfile
# with zipfile.ZipFile('../spam.zip','w') as myzip:
#     arr = os.listdir()
#     for i in arr:            # 127k
#         myzip.write(i)      # 压缩包存放目录和列出文件的目录不能一样,否则会将压缩包循环压缩?
# with zipfile.ZipFile('spam.zip','w') as myzip:
#     arr = os.listdir()
#     for i in arr:
#         myzip.write(i)      # 压缩文件特别大 9,3455k
with zipfile.ZipFile('spam.zip','w',zipfile.ZIP_DEFLATED) as myzip:
    arr = os.listdir()
    for i in arr:
        myzip.write(i)        # 66k  压缩文件中包含spam.zip
  • extrall() 解压缩文件
import zipfile
with zipfile.ZipFile('spam.zip','r') as myzip:
    myzip.extractall('./')   # 也可指定到其他目录
  • 使用shutil模块进行归档压缩
  • shutil.make_archive()
    参数1,创建的压缩文件名称;参数2,指定的压缩格式,zip,tar;参数3,要压缩的文件或文件夹路径
import shutil
shutil.make_archive('../a','tar','./') # 速度有点慢啊。。

16.8 时间模块 time

1.时间戳
2.时间字符串
3.时间元组

  • time.time() 获取当前系统的时间戳 重点 重要 表示从1970年1月1日0时0分0秒到现在的一个秒数
    目前可以计算到2038年
import time
res = time.time()
print(res) # 1633525962.9521518
  • time.ctime() 获取当前系统时间,时间字符串
import time
res = time.ctime()
print(res) # Wed Oct  6 21:21:03 2021
  • time.localtime() 获取当前系统时间,时间元组
import time
res = time.localtime()
print(res) # time.struct_time(tm_year=2021, tm_mon=10, tm_mday=6, tm_hour=21, tm_min=22, tm_sec=58, tm_wday=2, tm_yday=279, tm_isdst=0)
  • 时间字符串和时间元组可以通过时间戳来获取指定时间
import time
t = 1788525962.9521518
res = time.ctime(t)      # Fri Sep  4 20:46:02 2026
res = time.localtime(t)  # time.struct_time(tm_year=2026, tm_mon=9, tm_mday=4, tm_hour=20, tm_min=46, tm_sec=2, tm_wday=4, tm_yday=247, tm_isdst=0)
print(res)
  • 使用locatime获取的时间元组,格式化为 XX年XX月XX日 时:分:秒
import time
t = 1788525962.9521518
res = time.localtime(t)  # time.struct_time(tm_year=2026, tm_mon=9, tm_mday=4, tm_hour=20, tm_min=46, tm_sec=2, tm_wday=4, tm_yday=247, tm_isdst=0)
print(f'{res.tm_year}年{res.tm_mon}月{res.tm_mday}日 {res.tm_hour}时:{res.tm_min}分:{res.tm_sec}秒 星期{res.tm_wday}')
# 2026年9月4日 20时:46分:2秒 星期4
# 个位数补0      注意注意!!
res = str(res.tm_sec).zfill(2)
print(res)
  • strftime() 格式化时间 年 月 日 时 分 秒 星期 重点 重要
import time
res = time.strftime('%Y-%m-%d %H:%M:%S %w')
print(res)   # 2021-10-06 21:45:13 3
  • sleep(sec) 可以在给定的秒数内暂停当前线程的执行 重点 重要
    参数可以是浮点数
import time
print(time.strftime('%Y-%m-%d %H:%M:%S %w'))
time.sleep(5)
print(time.strftime('%Y-%m-%d %H:%M:%S %w'))
# 2021-10-06 21:52:49 3
# 2021-10-06 21:52:54 3
  • time.perf_counter() 计算程序的运行时间
import time
time.perf_counter()

# 10万次字符串比较,耗时
start = time.perf_counter()
for i in range(100000):
    if 'abc' > 'def':
        pass
end = time.perf_counter()
print(end - start)      # 0.03017492699999999

16.9 日历模块 calendar

pythan文档多看看

  • calendar.monthrange(y,m)
    返回指定年份和月份的数据,月份的第一天是周几,和月份的天数
import calendar
res = calendar.monthrange(2021,10)
days = res[1] # 当前月份的天数
w = res[0]+1  # 当前月份第一天是周几
print(res)
  • 实现日历信息的输出
import calendar
res = calendar.monthrange(2021,10)
days = res[1] # 当前月份的天数 31
w = res[0]+1  # 当前月份第一天是周几 5
print(' 一  二   三  四   五  六  日 ')
d = 1
print('====={2021}年{10}月=====')
print('*'*28)
while d <= days:
    for i in range(1,8):
        if d > days or (i < w and d == 1 ):
            print(' '*4,end='')    # 空格数量要与下面' {:0>2d} '的一致,数量相当于\t
        else:
            print(' {:0>2d} '.format(d),end='')
            d += 1
    print()

内置模块练习 万年历

默认显示当前月,上一月,下一月,可以指定年月

import calendar

def showdate(y,m):
    res = calendar.monthrange(y,m)
    days = res[1] # 当前月份的天数 
    w = res[0]+1  # 当前月份第一天是周几 
    print(f'========={y}年{m}月=========')
    print(' 一  二   三  四   五  六  日 ')
    d = 1
    print('*'*28)
    while d <= days:
        for i in range(1,8):
            if d > days or (i < w and d == 1 ):
                print(' '*4,end='')    # 空格数量要与下面' {:0>2d} '的一致,数量相当于\t
            else:
                print(' {:0>2d} '.format(d),end='')
                d += 1
        print()
    print('*' * 28)
    
import time,os
res = time.localtime()
y = res.tm_year
m = res.tm_mon
print('check the current calendar ')
showdate(y,m)
while True:
    os.system('clear')
    showdate(y, m)
    print('<上一月> : 0 , <下一月> : 1')
    print('choose year and month you want : 3')
    print('other keys to exit')
    i = input('please select : ')
    if i == '0':
        m -= 1
        if m == 0:
            m = 12
            y -= 1
    elif i == '1':
        m += 1
        if m == 13:
            m = 1
            y += 1
    elif i == '3':
        y = int(input('enter the year : '))
        m = int(input('enter the month : '))
    else:
        break

 16.10 requests模块

import requests

# 发送请求
re=requests.get('http:/baidu.com/')

# 返回网页内容
print(re.text)

每次调用requests请求后,返回一个response对象,包含具体的响应信息:

close(),关闭与服务器的连接
content,返回响应的内容,以字节为单位
cookies,返回一个CookieJar对象,包含从服务器发回的cookie
headers,返回响应头,字典格式
history    返回包含请求历史的响应对象列表(url)
is_permanent_redirect    如果响应是永久重定向的 url,则返回 True,否则返回 False
is_redirect    如果响应被重定向,则返回 True,否则返回 False
iter_content()    迭代响应
iter_lines()    迭代响应的行
json()    返回结果的 JSON 对象 (结果需要以 JSON 格式编写的,否则会引发错误)
links    返回响应的解析头链接
next    返回重定向链中下一个请求的 PreparedRequest 对象
ok    检查 "status_code" 的值,如果小于400,则返回 True,如果不小于 400,则返回 False
raise_for_status()    如果发生错误,方法返回一个 HTTPError 对象
reason    响应状态的描述,比如 "Not Found" 或 "OK"
request    返回请求此响应的请求对象
status_code    返回 http 的状态码,比如 404 和 200(200 是 OK,404 是 Not Found)
text    返回响应的内容,unicode 类型数据
url    返回响应的 URL

requests 方法

delete(url, args)    发送 DELETE 请求到指定 url
get(url, params, args)    发送 GET 请求到指定 url
head(url, args)    发送 HEAD 请求到指定 url
patch(url, data, args)    发送 PATCH 请求到指定 url
post(url, data, json, args)    发送 POST 请求到指定 url
put(url, data, args)    发送 PUT 请求到指定 url
request(method, url, args)    向指定的 url 发送指定的请求方法

对于 POST 请求,一般就是提交一个表单,data 当中,就是需要传递的表单信息,是一个字典类型的数据。一般格式如下:

requests.post(url, data={key: value}, json={key: value}, args

* url 请求 url。
* data 参数为要发送到指定 url 的字典、元组列表、字节或文件对象。
* json 参数为要发送到指定 url 的 JSON 对象。
* args 为其他参数,比如 cookies、headers、verify等。

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值