python20-常用包介绍下

    xiaoxiao2022-07-07  196

    5.5 os

    5.5.1 os – 操作系统相关

    跟操作系统相关,主要是文件操作 与系统相关的操作,主要包含在三个模块里 os, 操作系统目录相关os.path, 系统路径相关操作shutil, 高级文件操作,目录树的操作,文件赋值,删除,移动 路径: 绝对路径: 总是从根目录上开始相对路径: 基本以当前环境为开始的一个相对的地方 import os # getcwd() 获取当前的工作目录 # 格式:os.getcwd() # 返回值:当前工作目录的字符串 # 当前工作目录就是程序在进行文件相关操作,默认查找文件的目录 mydir = os.getcwd() print(mydir) --------------------- C:\Users\tf\python全栈 # chdir() 改变当前的工作目录 # change directory # 格式:os.chdir(路径) # 返回值:无 os.chdir("C:/Users/") mydir = os.getcwd() print(mydir) ------------------- C:\Users # listdir() 获取一个目录中所有子目录和文件的名称列表 # 格式:os.listdir(路径) # 返回值:所有子目录和文件名称的列表 ld = os.listdir() print(ld) # makedirs() 递归创建文件夹 # 格式:os.makedirs(递归路径) # 返回值:无 # 递归路径:多个文件夹层层包含的路径就是递归路径 例如 a/b/c... # system() 运行系统shell命令 # 格式:os.system(系统命令) # 返回值:打开一个shell或者终端界面 # 一般推荐使用subprocess代替 # ls是列出当前文件和文件夹的系统命令 rst = os.system("ls") print(rst) # 在当前目录下创建一个dana.haha 的文件 rst = os.system("touch dana.haha") print(rst) 在这里插入代码片

    5.8.1random

    随机数所有的随机数都是伪随机 import random # random() 获取0-1之间的随机小数 # 格式:random.random() # 返回值:随机0-1之间的小数 print(random.random()) --------------------------- 0.953877407089044 # choice() 随机返回序列中的某个值 # 格式:random.choice(序列) # 返回值:序列中的某个值 l = [str(i)+"haha" for i in range(10)] print(l) rst = random.choice(l) print(rst) -------------------------- ['0haha', '1haha', '2haha', '3haha', '4haha', '5haha', '6haha', '7haha', '8haha', '9haha'] 1haha # shuffle() 随机打乱列表 # 格式:random.shuffle(列表) # 返回值:打乱顺序之后的列表 l1 = [i for i in range(10)] print(l1) random.shuffle(l1) print(l1) ------------------------ [0, 1, 2, 3, 4, 5, 6, 7, 8, 9] [3, 8, 2, 9, 0, 1, 5, 6, 4, 7] # randint(a,b): 返回一个a到b之间的随机整数,包含a和b print(random.randint(0,100)) --------------------------------------- 42
    最新回复(0)