How can I safely create a nested directory?

前端 未结 27 2612
旧时难觅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:36

    You have to set the full path before creating the directory:

    import os,sys,inspect
    import pathlib
    
    currentdir = os.path.dirname(os.path.abspath(inspect.getfile(inspect.currentframe())))
    your_folder = currentdir + "/" + "your_folder"
    
    if not os.path.exists(your_folder):
       pathlib.Path(your_folder).mkdir(parents=True, exist_ok=True)
    

    This works for me and hopefully, it will works for you as well

提交回复
热议问题