如何在 Python 中模拟 `mkdir -p` 功能?
Python mkdir -p 等效
要在 Python 中模拟 shell 的 mkdir -p 功能,有多种方法可用。
Python 3.5 及更高版本
Python 3.5 引入了pathlib.Path.mkdir 函数,其中包含parents 和exist_ok 参数。通过将parents设置为True并将exist_ok设置为True,它会创建目录和任何不存在的父目录,而不会引发错误:
<code class="python">import pathlib pathlib.Path("/tmp/path/to/desired/directory").mkdir(parents=True, exist_ok=True)</code>
Python 3.2及更高版本
对于 Python 3.2 及更高版本,os.makedirs 函数有一个可选的第三个参数,exist_ok,可以将其设置为 True 以实现相同的行为:
<code class="python">import os os.makedirs("/tmp/path/to/desired/directory", exist_ok=True)</code>
早期 Python 版本
对于旧版本的 Python,您可以使用 os.makedirs 函数并在目录已存在时捕获 OSError 异常,使用以下代码:
<code class="python">import errno import os def mkdir_p(path): try: os.makedirs(path) except OSError as exc: # Python ≥ 2.5 if exc.errno == errno.EEXIST and os.path.isdir(path): pass # possibly handle other errno cases here, otherwise finally: else: raise</code>
以上是如何在 Python 中模拟 `mkdir -p` 功能?的详细内容。更多信息请关注PHP中文网其他相关文章!

热AI工具

Undresser.AI Undress
人工智能驱动的应用程序,用于创建逼真的裸体照片

AI Clothes Remover
用于从照片中去除衣服的在线人工智能工具。

Undress AI Tool
免费脱衣服图片

Clothoff.io
AI脱衣机

Video Face Swap
使用我们完全免费的人工智能换脸工具轻松在任何视频中换脸!

热门文章

热工具

记事本++7.3.1
好用且免费的代码编辑器

SublimeText3汉化版
中文版,非常好用

禅工作室 13.0.1
功能强大的PHP集成开发环境

Dreamweaver CS6
视觉化网页开发工具

SublimeText3 Mac版
神级代码编辑软件(SublimeText3)

使用FiddlerEverywhere进行中间人读取时如何避免被检测到当你使用FiddlerEverywhere...

如何在10小时内教计算机小白编程基础?如果你只有10个小时来教计算机小白一些编程知识,你会选择教些什么�...

攻克Investing.com的反爬虫策略许多人尝试爬取Investing.com(https://cn.investing.com/news/latest-news)的新闻数据时,常常�...

Python3.6环境下加载pickle文件报错:ModuleNotFoundError:Nomodulenamed...

使用Scapy爬虫时管道文件无法写入的原因探讨在学习和使用Scapy爬虫进行数据持久化存储时,可能会遇到管道文�...
