记录了几个常用的os模块功能,更多的可以参考【菜鸟教程】
函数 | 功能 |
---|---|
os.chdir() | 改变工作目录 |
os.getcwd() | 当前工作目录 |
os.listdir() | 返回path目录下文件名和文件夹 |
os.mkdir() | 创建一个文件夹 |
os.open() | 打开文件(可选参数) |
os.remove() | 删除文件——删除文件夹抛出异常 |
os.rmdir() | 删除空目录——不为空抛出异常 |
os.removedirs() | 递归删除目录 |
os.rename(1,2) | 重命名,从1改为2 |
os.path.abspath() | 返回绝对路径 |
os.path.basename() | 返回文件名 |
os.path.dirname() | 返回文件路径 |
os.path.exists() | 存在:True;否则 :False。 |
os.path.isfile(path) | 判断路径是否为文件 |
os.path.isdir(path) | 判断路径是否为目录 |
os.path.join() | 把目录和文件名合成一个路径 |
os.path.split() | 把路径分割成 dirname 和 basename,返回一个元组 |
os.path.splitext(path) | 分割路径,返回路径名和文件扩展名的元组 |
root ,dirs,files = os.walk(Root) 依次遍历Root下目录,返回三个值
root : 当前遍历根目录
dirs :目录下文件夹
files : 目录下文件
返回值 | |||
第一轮 | root | Root | |
dirs | Dir1,Dir2 | ||
files | [ ] | ||
第二轮 | root | Dir1 | |
dirs | [ ] | ||
files | file1, file2 | ||
第三轮 | root | Dir2 | |
dirs | Dir3 | ||
files | file3 |