Python_6:常用模块

本文深入解析Python中的各种模块,包括random、math、os、os.path、sys、hashlib、time及datetime模块的功能与使用方法,覆盖从随机数生成到时间日期操作,再到文件系统管理与加密算法的广泛应用。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

一、基础知识

1.1 什么是模块

定义的xx.py文件就是模块

1.2 模块的分类

根据模块的创建者分类

  • 系统内置模块

  • 第三方模块

    由其他程序员、组织、公司提供。

    第三方模块模块需要使用的,首先需要安装模块。

    • 在线安装:pip install module_name
    • 离线安装包安装:
      1. 下载、解压
      2. cmd:python install setup.py
  • 自定义模块

1.3 模块的导入

使用import关键字导入

  • import 模块名称

  • import 模块名称 as alias(别名) # 使用as做别名

    >>> import random as r
    
    >>> r.randint(1,10)
    1
    >>> r.randint(1,10)
    5
    
  • import a.b #导入a包下的b包

  • import a.b as alias

    >>> import os.path
    >>> import os.path as osp
    
  • from 包 import 模块名称

    python3强烈推荐这种方法,可以直接使用模块名调用

    >>> from functools import partial
    >>> new_int = partial(int,base=16)
    

二、random模块

  • random()

    产生一个0~1内的随机数

    >>> random.random()
    0.5187700781367581
    
  • randint()

    产生随机整数[m, n]

    >>> random.randint(1,500)
    470
    
  • choice()

    在序列(seq)中随机筛选一个元素

    >>> random.choice("wang")
    'a'
    
  • uniform()

    产生的基于正态分布的随机数

    >>> random.uniform(1,10)
    3.036474847465443
    

三、math模块

常用属性或方法

  • ceil()

    向上取整

    >>> math.ceil(3.14)
    4
    
  • floor

    向下取整

    >>> math.floor(-3.14)
    -4
    
  • e

    自然常数e

    >>> math.e
    2.718281828459045
    
  • fabs()

    求绝对值,等价于全局函数abs()

    >>> math.fabs(-1.414)
    1.414
    
  • fmod()

    求模运算

    >>> math.fmod(9,2)
    1.0
    
  • isnan()

    Return True if x is a NaN (not a number), and False otherwise.

    >>> math.isnan(math.e)
    False
    
  • pi

    >>> math.pi
    3.141592653589793
    
  • pow

    幂运算

    >>> math.pow(2,2)
    4.0
    
  • sqrt

    >>> math.sqrt(2)
    1.4142135623730951
    

四、os模块

常用方法和属性

  • chdir(path)

    修改当前工作目录

    >>> import os
    >>> os.path.abspath(os.curdir)
    'D:\\Python\\project'
    
    >>> os.chdir("d:\\")
    
    >>> os.path.abspath(os.curdir)
    'd:\\'
    
  • curdir

    获取当前目录的相对路径

    >>> os.curdir
    '.'
    >>> os.path.abspath(os.curdir)  #绝对路径
    'd:\\'
    
  • chmod()

    修改权限,Linux

  • cpu_count()

返回cpu的线程数

>>> os.cpu_count()
8
  • getcwd()

    获取当前目录的绝对路径

    >>> os.getcwd()
    'D:\\Python\\project'
    
  • getpid()

  • 获取当前进程的编号

>>> os.getpid()
11756
  • getppid()

    获取当前进程的父进程的编程

    >>> os.getppid()
    4900
    
  • kill()

    通过进程编号杀死进程

    kill(pid, signal, /)
        Kill a process with a signal.
    
  • os.linesep

    对应系统的换行符

    >>> os.linesep
    '\r\n'
    
  • listdir()

  • 返回对应目录下的文件及文件夹

>>> os.listdir()
['10匿名函数.py',……
  • makedirs()

    创建目录,支持多层创建

    >>> os.makedirs("d:\\Python\\project\\1\\1")
    
  • mkdir() # 创建目录,只支持一层创建

    >>> os.makedirs("d:\\Python\\project\\1\\1")
    >>> os.mkdir("d:\\Python\\project\\2\\2")
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    FileNotFoundError: [WinError 3] 系统找不到指定的路径。: 'd:\\Python\\project\\2\\2'
    >>> os.mkdir("d:\\Python\\project\\2")
    
  • open()

    创建文件,等价于全局open

    open(path, flags, mode=511, *, dir_fd=None)
    
  • pathsep

    获取环境变量的分隔符 window ; linux :

    >>> os.pathsep
    ';'
    
  • sep

    路径的分隔符 window \ linux /

    >>> os.sep
    '\\'
    
  • remove(path)

    删除文件

    >>> os.remove("d:\\Python\\project\\1.txt")
    
  • removedirs()

    删除目录,支持多层删除,递归删除

    >>> os.removedirs("d:\\Python\\project\\1\\1")
    
  • system

    执行终端命令

    >>> os.system("ipconfig")
    

五、os.path模块

常用方法和属性

  • abspath(相对路径)

    返回路径对应的绝对路径 dirname + basename = abspath

    >>> path.abspath(os.curdir)
    'C:\\Users\\--'
    
  • basename()

    文件名称

    >>> path.basename("D:\Python\project\新建文本文档.txt")
    '新建文本文档.txt'
    
  • dirname()

    文件所在的目录

    >>> path.dirname("D:\Python\project\新建文本文档.txt")
    'D:\\Python\\project'
    
  • curdir

    当前目录

    >>> path.curdir
    '.'
    
  • exists()

    判断文件或者目录是否存在

    >>> path.exists("D:\Python\project")
    True
    
  • getctime()

    创建时间:返回当前时间的时间戳(1970纪元后经过的浮点秒数)。

    >>> path.getctime("D:\Python\project")
    1583735447.3198295
    
  • getmtime()

    获取修改时间

    >>> path.getmtime("D:\Python\project")
    1585294228.721111
    
  • getsize()

    获取文件的大小,单位是字节

    >>> path.getsize("D:\Python\project")
    8192
    
  • isdir(path)

    判断path是不是目录

    >>> path.isdir("D:\Python\project")
    True
    >>> path.isdir("D:\Python\project\11os.py")
    False
    
  • isfile(path)

    判断path是不是普通文件(Test whether a path is a regular file)

    >>> path.isfile("D:\Python\project")
    False
    
    >>> path.isfile("D:\Python\project\新建文本文档.txt")
    True
    
    #注意:
    >>> path.isfile("D:\Python\project\11os.py")
    False
    
  • isabs

    判断是不是绝对路径

    >>> path.isabs("\Python\project\1函数的调用.py")
    True
    >>> path.isabs("1函数的调用.py")
    False
    >>> path.isabs("\project\1函数的调用.py")
    True
    
  • islink()

    判断是不是链接

  • ismount()

    判断是不是挂载文件

  • join(p1, p2)

    拼接路径

    >>> path.join("d:\\","1.txt")
    'd:\\1.txt'
    
  • sep

    路径分割符

    >>> path.sep
    '\\'
    
  • split

    分割路径 abspath = dirname + basename

    >>> path.split("D:\Python\project\新建文本文档.txt")
    ('D:\\Python\\project', '新建文本文档.txt')
    
  • realpath # 返回真实路径

    >>> path.realpath("D:\Python\project\新建文本文档.txt")
    'D:\\Python\\project\\新建文本文档.txt'
    

六、sys模块

常用方法和属性

  • api_version

    python的内部版本号

    >>> sys.api_version
    1013
    
  • argv

    接收脚本参数的。第一个参数是脚本名称

    import sys
    
    print(sys.argv)
    
    
    #结果:
    D:\Python\project>13脚本参数.py
    ['D:\\Python\\project\\13脚本参数.py']
    
    D:\Python\project>13脚本参数.py 1,2,3,"wang"
    ['D:\\Python\\project\\13脚本参数.py', '1,2,3,wang']
    
    D:\Python\project>13脚本参数.py 1 "王"
    ['D:\\Python\\project\\13脚本参数.py', '1', '王']
    
  • copyright

    输出cpython的版权信息

    >>> sys.copyright
    'Copyright (c) 2001-2020 Python Software Foundation.\nAll Rights Reserved.\n\nCopyright (c) 2000 BeOpen.com.\nAll Rights Reserved.\n\nCopyright (c) 1995-2001 Corporation for National Research Initiatives.\nAll Rights Reserved.\n\nCopyright (c) 1991-1995 Stichting Mathematisch Centrum, Amsterdam.\nAll Rights Reserved.'
    
  • sys.exit()

    退出系统

  • getdefaultencoding()

    获取默认编码,默认是utf-8

    >>> sys.getdefaultencoding()
    'utf-8'
    
  • setfilesystemencoding()

    更改编码格式

  • getrecursionlimit()

    获取python对于递归的限制层数

    >>> sys.getrecursionlimit()
    1000
    
  • setrecursionlimit(num)

    重新设置递归的限制层数

  • getrefcount(对象)

    获取对象的引用计数,垃圾回收机制中

    >>> ls = [1,2,3]
    >>> sys.getrefcount(ls)
    2
    >>> sys.getrefcount(ls)
    2
    >>> ls1 = ls
    >>> sys.getrefcount(ls)
    3
    
  • getwindowsversion()

    获取窗口的版本信息

    >>> sys.getwindowsversion()
    sys.getwindowsversion(major=10, minor=0, build=18363, platform=2, service_pack='')
    
  • version()

    获取版本信息

    >>> sys.version
    '3.8.2 (tags/v3.8.2:7b3ab59, Feb 25 2020, 23:03:10) [MSC v.1916 64 bit (AMD64)]'
    

python的垃圾回收原理:引用计数为主,以标记清除和分代收集为辅

程序:遍历输出指定路径下的所有文件的文件名

import os
from os import path
import sys

def show(url):
	files = os.listdir(url)
	for f in files:
		real_path = path.join(url,f)
		#判断是否为文件。如果是,输出绝对路径
		if path.isfile(real_path):
			print(path.abspath(real_path))
		#如果是目录,递归调用自身函数
		elif path.isdir(real_path):
			show(real_path)
show(sys.argv[1])  #文件路径由脚本参数提供

七、hashlib模块

7.1加密算法的分类

以算法是否可逆划分

  • 可逆算法

    • 对称加密:解密和加密用同一把密钥

      常见:DES

    • 非对称加密:加密和解密使用是一对秘钥(公钥、私钥)

      常见:RSA

  • 不可逆算法(hash算法)

    特点:不可逆、加密所得值唯一

    常见:md5、sha256、sha1

7.2 hashlib模块的使用

  1. 创建算法对象(md5 sha256),返回一个算法对象

    md5 = hashlib.md5("123456".encode("utf-8"))
    
  2. 如果不做盐值混淆,直接调用hexdigest()方法

    md5.hexdigest()
    
  3. 盐值混淆

    hash容易碰撞破解,一般建议使用盐值混淆(md5.com)

    md5.update(salt)
    

7.3 hmac模块

hmac是一个哈希加密库,而且使用对称加密

首先会使用对称加密(秘钥就是盐值),之后将加密后的数据再做一次hash加密,盐值混淆,所以整个结果十分安全。

>>> m = hmac.new("12345".encode("utf-8"),"wang".encode("utf-8"),"md5")

>>> m
<hmac.HMAC object at 0x00000188AEA175E0>

>>> m.hexdigest()
'e8f56c71fba4f2c74efb591ca3f7fb45'

其中,12345是所要加密的内容,wang是盐值。

八、time模块

python提供操作时间和日期的模块

8.1常用方法和属性

  • asctime()

    获取当前时间

    >>> time.asctime()
    'Sat Mar 28 00:39:43 2020'
    
  • ctime()

    获取当前时间

    >>> time.ctime()
    'Sat Mar 28 00:40:04 2020'
    
  • localtime()

    本地时间,方便于自己完成格式化

    >>> time.localtime()
    time.struct_time(tm_year=2020, tm_mon=3, tm_mday=28, tm_hour=0, tm_min=40, tm_sec=38, tm_wday=5, tm_yday=88, tm_isdst=0)
    
  • sleep()

    休眠时间,单位是秒

  • time()

    获取当前时间戳

    >>> time.time()
    1585327278.0334048
    
  • strptime

    将一个特定格式的时间字符串转换为时间对象

    Commonly used format codes:
    
    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.
    
    >>> t = "2020/3/28"
    >>> t
    '2020/03/28'
    >>> time.strptime(t,"%Y/%m/%d")
    time.struct_time(tm_year=2020, tm_mon=3, tm_mday=28, tm_hour=0, tm_min=0, tm_sec=0, tm_wday=5, tm_yday=88, tm_isdst=-1)
    
  • strftime

    将一个时间对象格式化为特定的字符串

    %Y  Year with century as a decimal number.
    %m  Month as a decimal number [01,12].
    %d  Day of the month as a decimal number [01,31].
    %H  Hour (24-hour clock) as a decimal number [00,23].
    %M  Minute as a decimal number [00,59].
    %S  Second as a decimal number [00,61].
    %z  Time zone offset from UTC.
    %a  Locale's abbreviated weekday name.
    %A  Locale's full weekday name.
    %b  Locale's abbreviated month name.
    %B  Locale's full month name.
    %c  Locale's appropriate date and time representation.
    %I  Hour (12-hour clock) as a decimal number [01,12].
    %p  Locale's equivalent of either AM or PM.
    
    >>> time.strftime("%Y-%m-%d")
    '2020-03-28'
    

8.2 datetime模块

对time模块的补充

常用datetime模块的子模块datetime

  • now()
>>> from datetime import datetime
>>> datetime.now
<built-in method now of type object at 0x00007FFAD49D7530>
>>> datetime.now()
datetime.datetime(2020, 3, 28, 0, 58, 39, 451909)
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值