How can I safely create a nested directory?

前端 未结 27 2621
旧时难觅i
旧时难觅i 2020-11-22 00:07

What is the most elegant way to check if the directory a file is going to be written to exists, and if not, create the directory using Python? Here is what I tried:

27条回答
  •  鱼传尺愫
    2020-11-22 00:54

    You can both create a file, and all its parent directories in 1 command with fastcore extension to pathlib: path.mk_write(data)

    from fastcore.utils import Path
    Path('/dir/to/file.txt').mk_write('Hello World')
    

提交回复
热议问题