python常用内置模块
OS模块
import os
print(dir(os)) #返回一个列表包括 os模块的所有函数名
print(help(os)) #返回所有os模块的所有内容
print(help(os.getcwd))
print(help('os.getcwd')) # 使用字符串也可以
os.name #返回python运行的环境系统
#nt:Windows
#posix:Linux 和 Mac OS
#java:Java 虚拟机环境
os.curdir #当前路径
#.
os.sep #文件分隔符
os.getcwd() #获取当前工作路径
os.chdir('D:/Pycharm') #切换工作路径,将工作目录切换到'D:/Pycharm'
os.environ #获取所有的环境变量
os.getlogin() #返回通过控制终端进程进行登录的用户名
os.mkdir('test') # 创建一个新的文件价夹,不能创建多级的文件夹
#当文件夹已经存在时会报错FileExistsError
#创建多级的文件夹会报错FileNotFoundError
os.makedirs('a/b') #创建多级目录
#创建a文件夹,并且在a文件夹下创建b文件夹
os.rmdir('a') #删除空文件夹,非空则报错
os.remove('a.txt') #删除文件
os.path模块
os.path #获取当前环境的路径
#<module 'ntpath' from 'D:\\anaconda3\\envs\\test1\\lib\\ntpath.py'>
os.path.abspath(path) #返回路径 path 的绝对路径
os.path.exists(path) #判断该路径或文件是否存在 return:Ture、False
os.path.getatime(path) #返回path的最后访问时间,返回的时间为秒(时间戳),可以利用tiem转换成常用的时间格式
print(os.path.getatime('a'))
t = os.path.getatime('a') # 获取时间戳
tupTime = time.localtime(t) # 将时间戳转换成本地时间
stadardTime = time.strftime("%Y-%m-%d %H:%M:%S", tupTime) # 转换成对应的时间格式
print(stadardTime) #2023-09-14 17:41:04
os.path.getsize(path) #获取文件的大小
os.path.split() # 将路径 path 拆分为一对,即 (head, tail),类型为元组
a = os.path.split('D:/aa/bb')
print(type(a)) # <class 'tuple'>
print(a) # ('D:/aa', 'bb') 头部和尾部
# 当最后为’/‘时
a = os.path.split('D:/aa/bb/')
print(a) # ('D:/aa/bb', '') 尾部为空
# 当路径path中没有路径的时候
a = os.path.split('aa')
print(a) # ('', 'aa') # 头部为空
# 当传入的路径为空时
a = os.path.split( '')
print(a) # ('', '') # 头部和尾部均为空
os.path.isdir() # 判断文件路径是否存在 返回布尔值
for file in os.listdir('jackguo/movies/'): #显示⽂件夹内所有⽂件
print(file)
results = os.path.splitext(file) #获取⽂件后缀名
print(results[1])
os.open模块
os.open(file, flags[, mode])
'''
file 文件名
flags 模式
mode 可选参数, mode 设置其权限状态
'''
flags – 该参数可以是以下选项,多个使用 “|” 隔开:
os.O_RDONLY: 以只读的方式打开
os.O_WRONLY: 以只写的方式打开
os.O_RDWR : 以读写的方式打开
os.O_NONBLOCK: 打开时不阻塞
os.O_APPEND: 以追加的方式打开
os.O_CREAT: 创建并打开一个新文件
os.O_TRUNC: 打开一个文件并截断它的长度为零(必须有写权限)
os.O_EXCL: 如果指定的文件存在,返回错误
os.O_SHLOCK: 自动获取共享锁
os.O_EXLOCK: 自动获取独立锁
os.O_DIRECT: 消除或减少缓存效果
os.O_FSYNC : 同步写入
os.O_NOFOLLOW: 不追踪软链接
# 打开文件
fd = os.open("1.txt", os.O_RDWR|os.O_CREAT ) # 模式可以并存中间用 | 隔开
# 写入字符串
a = b"This is test" # 不能直接写入字符串否则会报错TypeError: a bytes-like object is required, not 'str'
os.write(fd,a)
# 关闭文件
os.close(fd)
print("关闭文件成功!!")
Time模块
import time
时间表示法
- 时间戳表示法: 即以整型或浮点型表示的是一个以秒为单位的时间间隔。这个时间的基础值是从1970年的1月1号零点开始算起。
- 格式化的时间字符串: 即以格式化字符串的格式输出时间形式。
- 元组格式表示法: 即一种Python的数据结构表示。这个元组有9个整型内容(不能少),分别表示不同的时间含义。
| 索引(Index) | 属性(Attribute) | 值(Values) |
|---|---|---|
| 0 | tm_year(年) | 比如2023 |
| 1 | tm_mon(月) | 1 - 12 |
| 2 | tm_mday(日) | 1 - 31 |
| 3 | tm_hour(时) | 0 - 23 |
| 4 | tm_min(分) | 0 - 59 |
| 5 | tm_sec(秒) | 0 - 61 |
| 6 | tm_wday(weekday) | 0 - 6(0表示周日) |
| 7 | tm_yday(一年中的第几天) | 1 - 366 |
| 8 | tm_isdst(是否是夏令时) | 默认为-1 |
time.localtime([secs])
将一个时间戳转换为当前时区的struct_time。secs参数未提供,则以当前时间为准。
print(time.localtime())
#time.struct_time(tm_year=2023, tm_mon=9, tm_mday=15, tm_hour=8, tm_min=43, tm_sec=46, tm_wday=4, tm_yday=258, tm_isdst=0)
time.time( )
返回当前时间的时间戳。
print(time.time())
#1694739155.2444901
time.ctime([secs])
把一个时间戳(按秒计算的浮点数)转化为time.asctime()的形式。参数未给默认time.time()为参数。
print(time.ctime())
# Fri Sep 15 08:54:22 2023
time.sleep()
休眠多少秒
time.strftime(format[, t])
把一个代表时间的元组或者struct_time(如由time.localtime()和time.gmtime()返回)转化为格式化的时间字符串。如果t未指定,将传入time.localtime()。
print(time.strftime("%Y-%m-%d %H:%M:%S")) #2023-09-15 09:11:36
time.sleep(5)
print(time.strftime("%Y-%m-%d %H:%M:%S")) #2023-09-15 09:11:41
格式
| 格式 | 含义 | 格式 | 含义 |
|---|---|---|---|
| %a | 本地(locale)简化星期名称 | %p | 本地am或者pm的相应符 |
| %A | 本地完整星期名称 | %S | 秒(01 - 61) |
| %b | 本地简化月份名称 | %U | 一年中的星期数。(00 - 53星期天是一个星期的开始。) |
| %B | 本地完整月份名称 | %w | 一个星期中的第几天(0 - 6,0是星期天) |
| %c | 本地相应的日期和时间表示 | %W | 和%U基本相同,不同的是%W以星期一为一个星期的开始。 |
| %d | 一个月中的第几天(01 - 31) | %x | 本地相应日期 |
| %H | 一天中的第几个小时(24小时制,00 - 23) | %X | 本地相应时间 |
| %I | 第几个小时(12小时制,01 - 12) | %y | 去掉世纪的年份(00 - 99) |
| %j | 一年中的第几天(001 - 366) | %Y | 完整的年份 |
| %m | 月份(01 - 12) | %Z | 时区的名字(如果不存在为空字符) |
| %M | 分钟数(00 - 59) | %% | ‘%’字符 |
注意点
这两个time不一样
import time
from datetime import time #最好不这样写
import datetime #直接这样写
random模块
import random
random.random()
生成一个随机的浮点数,范围是在0.0~1.0之间
print(random.random()) #0.9585276688812329
random.randint(a, b)
生成一个a到b之间的随机整数
print(random.randint(1, 10)) #包含a,b
random.uniform(a, b)
生成一个a到b之间的随机浮点数
print(random.uniform(2.5, 5.5)) #4.779218148250635
random.choice(seq)
从序列seq中随机选择一个元素
print(random.choice(['A', 'B', 'C', 'D']))
random.sample(seq,k)
从序列seq中随机选择k个元素并返回一个列表
print(random.sample(['A', 'B', 'C', 'D'],2)) #['A', 'B']
random.randrange([start], stop[, step])
用于从range(start, stop, step)中随机选择一个数
print(random.randrange(0,10,2)) #[0,10)步长为2
案例:生成6位数验证码
yzm = [random.randint(0,9) for _ in range(6)]
print(yzm) #[1, 8, 8, 3, 1, 5]