首页 > 解决方案 > 在 Python 中安装 -D /dev/null path_file 功能

问题描述

在 BASH 中,要创建文件及其可能具有的父目录,可以这样做install -D /dev/null file_name

例如:

install -D /dev/null /var/tmp/an-example/example_file.txt

将创建完整的目录结构/var/tmp/an-example/和空文件example_file.txt

我想知道在 Python 中是否有一种简单的 Pythonic 方式来做同样的事情,除了使用子进程......

标签: pythonbashtouchmkdir

解决方案


我正在检查,在发布后我发现自己有一个简单的方法......

适用于 Python >= 3.5

from pathlib import Path
# ...

# creates directories structure, like mkdir -p <directories> would do
Path(file_with_path[:file_with_path.rfind("/")]).mkdir(parents=True, exist_ok=True)

# creates the empty file, as touch <filename> would do:
Path(file_with_path).touch()


推荐阅读