常用系统模块

常用系统模块,第1张

常用系统模块 常用系统模块 常用系统模块
  • os模块
import os

print(os.name)
print(os.getcwd()) # 获取当前目录
# os.listdir(文件夹路径)获取指定文件夹下所有文件和文件夹名(获取指定文件夹所有的内容)
print(os.listdir('./files'))
for n in os.listdir('./files'):
    if n[-4:] == '.txt':
        result = open('./files/'+n).read()
        print(result)
# 创建文件夹mkdir、makedirs
os.mkdir('./files/a')
os.makedirs('./files/aaa/bbb')
# 返回文件名
result = os.path.basename('./files/a')
print(result)
# os.path.exist(文件/文件夹路径)
# os。path.sp;itsxt(文件路径)文件名和后分离
数学模块
  • python 中和数字相关的类型有四种:int、float、bool、complex
import math
import cmath
# ai + b 复数,i虚数单位,i**2=-1,python中j是虚数单位
x = 2j + 3
y = 3j - 4
print(x + y)
print(x * y)

  • math模块
#小数转整数
math.ceil()#向大取整
math.floor()#向小取整
print(round())#四舍五入
print(abs(-1))
print(math.fabs(-1))
  • 随机模块
# 产生随机整数random。randint()产生a到b的随机数
print(random.randint(1, 2))
# 产生随机小数random。random()产生0到1 的随机小数
print(random.random())
print(random.random()*50+50)
# 再指定等差数列中随机获取一个数random.randrange(起点, 终点, 步长)
print(random.randrange(0, 100, 2))
  • 洗牌、抽牌
# 洗牌
num = [10, 20, 30, 40]
random.shuffle(num)
print(num)
# 抽牌
# random.choice()一个
# random.choices()多个
num = [10, 20, 30, 40]
result = random.choices(num, k=3)
print(result)
# random.sample(序列,k=数量)无放回

欢迎分享,转载请注明来源:内存溢出

原文地址: https://outofmemory.cn/zaji/5680252.html

(0)
打赏 微信扫一扫 微信扫一扫 支付宝扫一扫 支付宝扫一扫
上一篇 2022-12-17
下一篇 2022-12-17

发表评论

登录后才能评论

评论列表(0条)

保存