You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mac系统上使用Python创建文件夹?

macOS 环境下Python创建文件夹的实现方案

macOS 为类Unix系统,Python创建文件夹的逻辑与其他Unix系统完全一致,无需做系统适配,以下是两种可直接运行的极简实现:


方法一:使用 os 标准库(全Python版本兼容)

适合需要兼容Python 2.x或3.x早期版本的场景:

  • 单个文件夹创建(要求父目录已存在,否则抛出异常)
import os
# 替换为目标文件夹的绝对/相对路径
target_path = "/Users/你的用户名/Desktop/new_folder"
os.mkdir(target_path)
  • 多级文件夹递归创建(父目录不存在时自动创建,支持跳过已存在的文件夹)
import os
target_path = "/Users/你的用户名/Desktop/project/src/utils"
# exist_ok=True 避免文件夹已存在时的报错,不需要可移除该参数
os.makedirs(target_path, exist_ok=True)

方法二:使用 pathlib 标准库(Python 3.4+ 推荐)

面向对象的路径处理方式,代码可读性更高:

from pathlib import Path
target_path = Path("/Users/你的用户名/Desktop/new_folder")
# parents=True 开启递归创建父目录,exist_ok=True 跳过已存在的文件夹
target_path.mkdir(parents=True, exist_ok=True)

注意事项:

  • 填写相对路径时,文件夹会默认创建在Python脚本的运行工作目录下
  • 若出现权限报错,优先检查目标路径的写入权限,不要随意使用sudo运行脚本

内容的提问来源于stack exchange,提问作者Benjamin Reiser

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.03 11:18:01