资讯详情

Python Note -- Day 10. 内置模块

16 内置模块

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

通过pickle我们可以将程序中运行的对象信息保存到文件中并永久存储。

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

16.1 序列化模块 pickle

序列化是指可以python数据以文本或二进制的形式转换,也可以反序列化为原始数据

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 = 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中字典的定义规则和语法都很像 ——它也是互联网上通用的数据交换、数据传输和数据定义的数据格式

python中提供的json模块转换一些模块python数据对象,转换json格式的数据    json.dumps()    json.loads()        json.dump()    json.load() 
import json vars = {'a':1,'bbc':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,'bbcn':'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函数

  • 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 

16.3.2 常量

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

16.4 随机模块 random

  • random.random() 随机小数返回[0-1)
  • random.randrange([start],end,[step]) 随机获取指定范围内的整数 左闭右开
  • random.randint(start,end) 在指定范围内随机产生整数 都是封闭的,必须有两个参数
  • random.uniform(start,end) 获得指定范围内的随机小数
  • random.choice() 集合不能随机获取容器类型中的值
import randm
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长度列表,用于无重复的随机抽样

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() 将相对路径转为绝对路径 
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()

16.10 内置模块练习 万年历

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

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

标签: 6074连接器

锐单商城拥有海量元器件数据手册IC替代型号,打造 电子元器件IC百科大全!

锐单商城 - 一站式电子元器件采购平台