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

Deno的ensureDir方法对应的Python等价实现是什么?

Deno ensureDir/ensureDirSync 的Python等价实现

Deno的ensureDir(异步)和ensureDirSync(同步)核心作用是:确保指定路径的目录存在,若目录不存在则创建(包括所有必要的父目录);若目录已存在则不做任何操作,也不会抛出错误。以下是对应的Python实现:

同步版本(对应ensureDirSync)

方法1:使用pathlib.Path.mkdir()(Python 3.4+推荐)

pathlib是Python 3.4引入的面向对象文件路径操作模块,语法更简洁:

from pathlib import Path

# 确保./logs目录存在,不存在则创建(含父目录)
Path("./logs").mkdir(parents=True, exist_ok=True)
print("Success Created")
  • parents=True:允许创建路径中的所有缺失父目录
  • exist_ok=True:目录已存在时不抛出FileExistsError

方法2:使用os.makedirs()(传统方式)

import os

# 确保./logs目录存在,不存在则创建(含父目录)
os.makedirs("./logs", exist_ok=True)
print("Success Created")
  • exist_ok=True参数在Python 3.2及以上版本可用;若使用更低版本,需手动捕获FileExistsError:
import os

try:
    os.makedirs("./logs")
except FileExistsError:
    pass
print("Success Created")

异步版本(对应ensureDir)

Python标准库的异步IO模块asyncio本身没有提供异步的目录创建API,可通过以下两种方式实现:

方法1:使用aiofiles的异步文件操作

aiofiles是第三方库,提供异步的文件系统操作:

import asyncio
from aiofiles.os import makedirs

async def ensure_dir_async(path):
    await makedirs(path, exist_ok=True)
    print("Success Created")

# 运行异步函数
asyncio.run(ensure_dir_async("./logs"))

需先安装aiofiles:pip install aiofiles

方法2:用asyncio.to_thread包装同步方法(Python 3.9+)

将同步的目录创建操作放到单独线程中,实现异步调用:

import asyncio
from pathlib import Path

async def ensure_dir_async(path):
    # 把同步操作放到线程中执行
    await asyncio.to_thread(Path(path).mkdir, parents=True, exist_ok=True)
    print("Success Created")

asyncio.run(ensure_dir_async("./logs"))

内容的提问来源于stack exchange,提问作者Eliaz Bobadilla

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.01 12:20:50