gpt4 book ai didi

Python pathlib 如果目录不存在则创建目录

转载 作者:太空狗 更新时间:2023-10-29 17:13:11 91 4
gpt4 key购买 nike

如果我想指定一个路径来保存文件并创建该路径中不存在的目录,是否可以在一行代码中使用 pathlib 库来完成此操作?

最佳答案

是的,就是Path.mkdir :

pathlib.Path('/tmp/sub1/sub2').mkdir(parents=True, exist_ok=True)

来自 the docs :

If parents is true, any missing parents of this path are created asneeded; they are created with the default permissions without takingmode into account (mimicking the POSIX mkdir -p command).

If parents is false (the default), a missing parent raisesFileNotFoundError.

If exist_ok is false (the default), FileExistsError is raised if thetarget directory already exists.

If exist_ok is true, FileExistsError exceptions will be ignored (samebehavior as the POSIX mkdir -p command), but only if the last pathcomponent is not an existing non-directory file.

关于Python pathlib 如果目录不存在则创建目录,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50110800/

91 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com