Python os 模块

一、os模块

os 模块提供了非常丰富的方法用来处理文件和目录。

1
import os

shell

1
2
# 在操作系统命令行中运行一个shell命令
os.system(command)

操作工作目录

1
2
3
4
5
# 返回当前工作目录的路径
os.getcwd()

# 改变当前工作目录
os.chdir(path)

得到环境变量

1
os.environ

列出子目录

1
2
3
4
5
6
7
8
9
10
# 返回指定目录下的所有文件和子目录的名称列表
os.listdir(path)

# 生成子目录列表
sub_contents = [content.name for content in os.scandir(root_dir) if content.is_dir()]
sub_contents = [item for item in os.listdir(root_dir) if os.path.isdir(os.path.join(root_dir, item))]

# 生成子文件列表
sub_files = [file.name for file in os.scandir(root_dir) if file.is_file()]
sub_files = [item for item in os.listdir(root_dir) if os.path.isfile(os.path.join(root_dir, item))]

创建,删除,重命名目录

1
2
3
4
5
6
7
8
9
10
11
12
13
14
# 创建单个目录(父目录必须存在)
os.mkdir(path)
# 创建递归目录(允许创建父目录),路径,权限,目录存在不触发异常
os.makedirs(path, mode=511, exist_ok=True)

# 删除一个空目录
os.rmdir(path)
# 递归删除一个或多个空目录
os.removedirs(path)

# 重命名文件或目录
os.rename(old, new)
# 递归重命名文件或目录
os.renames(old, new)

二、os.path模块

检查路径,返回布尔值

1
2
3
4
5
6
7
8
# 检查路径path是否存在
os.path.exists(path)

# 检查路径path是否是一个文件
os.path.isfile(path)

# 检查路径path是否是一个目录
os.path.isdir(path)

拼接、分割路径

1
2
3
4
5
# 将多个路径拼接成一个路径
os.path.join(path1, path2, ...)

# 将路径path分割为目录和文件名
os.path.split(path)

返回值

1
2
3
4
5
6
7
8
9
10
11
# 返回path的绝对路径
os.path.abspath(path)

# 返回路径path的文件名部分
os.path.basename(path)

# 返回路径path的目录部分
os.path.dirname(path)

# 返回path的文件大小
os.path.getsize(path)

参考资料

  1. https://www.runoob.com/python/os-file-methods.html

延伸

  1. Pathlib: https://mp.weixin.qq.com/s/a19JmJOtSff2TqhTYaD8ig