一、OS模块
1.获取当前所在路径
os.getcwd()
[root@node4 etc]# cat test.py
import os
url = os.getcwd()
print(url)
结果如下:
[root@node4 etc]# python3 test.py
/usr/local/etc
2.切换路径
os.chdir()
[root@node4 etc]# cat test.py
import os
url = os.getcwd()
print(url)
os.chdir('../')
url = os.getcwd()
print(url)
结果如下:
[root@node4 etc]# python3 test.py
/usr/local/etc
/usr/local
os,path模块
1.os.path.join
作用:路径拼接
from os import path
a = "usr"
b = "local"
c = "nginx"
res = path.join(a,b,c)
print(res)
2.os.path.dirname
截取路径中文件所在的路径
from os import path
file = __file__
res = path.dirname(file)
print(file)
print(res)
3.os.path.basename
截取路径中文件的名称
from os import path
file = __file__
res = path.basename(file)
print(file)
print(res)
4.os.path.exists
测试文件或者目录是否存在
from os import path
file = path.basename(__file__)
print(path.exists(file))
5.os.path.isfile
测试是否为文件
from os import path
file = path.basename(__file__)
print(path.isfile(file))
6.os.path.isdir
测试是否为目录
7.os.path.split
切割路径和文件名
from os import path
print(path.split(__file__))
二、sys模块
sys是系统相关的模块
sys.path
寻找系统导入模块的时候所寻找的路径
>>> import sys
>>> sys.path
['', '/usr/lib64/python36.zip', '/usr/lib64/python3.6', '/usr/lib64/python3.6/lib-dynload', '/usr/local/lib64/python3.6/site-packages',
'/usr/local/lib/python3.6/site-packages', '/usr/lib64/python3.6/site-packages', '/usr/lib/python3.6/site-packages']
三、random
1.randomint.randint
生成指定范围内的整数,包含开头和结尾得整数
>>> print(random.randint(1,10))
4
>>> print(random.randint(1,10))
10
>>> print(random.randint(1,10))
8
>>> print(random.randint(1,10))
3
2.random.choice
在可迭代对象中随机抽取一个数据
3.random.sample
在可迭代对象中随机抽取多个数据
[root@node5 data]# cat test.py
#!/usr/bin/python3
import random
list = [1,2,3,4,5,6,7,8,9,10]
print(random.choice(list))
print(random.sample(list,3))
[root@node5 data]# ./test.py
3
[5, 2, 1]
[root@node5 data]# ./test.py
7
[3, 4, 2]
[root@node5 data]# ./test.py
6
[10, 7, 6]
[root@node5 data]# ./test.py
4
[7, 3, 1]
[root@node5 data]# ./test.py
8
[1, 6, 10]
四、datetime
1.打印当前时间
>>> import datetime as dt
>>> print(dt.datetime.now())
2021-04-14 23:17:01.612571
2.创建一个日期
>>> print(dt.date(2021,1,1))
2021-01-01
3.创建一个时间
>>> print(dt.time(18))
18:00:00
>>> print(dt.time(18,20,22))
18:20:22
五、time模块
1.time.time
从1970-1-1到现在得秒数
>>> print(time.time())
1618414013.7248337
2.time.strftime
按照指定得格式输出时间
>>> print(time.strftime("%Y-%m-%d"))
2021-04-14
>>> print(time.strftime("%H"))
23
>>> print(time.strftime("%H:%M:%S"))
23:30:52
六、UUID
生成全局唯一ID
UUID1
>>> import uuid
>>> print(uuid.uuid1())
fce8157c-9df3-11eb-b3fb-000c297bd39e
>>> print(uuid.uuid1())
fea94822-9df3-11eb-b3fb-000c297bd39e
UUID4 常用
>>> print(uuid.uuid4())
ec9d6ca0-cb4b-450e-ace2-be842f0aa00f
>>> print(uuid.uuid4())