python - 在 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 方式来做同样的事情,除了使用子进程......
解决方案
我正在检查,在发布后我发现自己有一个简单的方法......
适用于 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()
推荐阅读
- google-chrome - 如何找出哪个应用程序添加了 chrome 扩展?
- javascript - 在 Angular 中使用了对象标签但未找到相机
- c++ - 多态中的函数对象
- android - Androidx CardView 未在所有设备中按预期显示圆形图像
- postgresql - MULTILINESTRING 附近的 rgeo 点
- php - WordPress主页更改不起作用
- python - “无法找到用于 ipykernel 启动的内核规范”错误在我在虚拟工作室上运行时发生
- javascript - 邮递员在使用 GET 请求时返回空
- javascript - 如何在我的 AJAX 调用中恢复和传递多个 php 变量
- android - WorkManager 现有工作策略 APPEND_OR_REPLACE 未按预期运行