How can I safely create a nested directory?

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

    Call the function create_dir() at the entry point of your program/project.

    import os
    
    def create_dir(directory):
        if not os.path.exists(directory):
            print('Creating Directory '+directory)
            os.makedirs(directory)
    
    create_dir('Project directory')
    

提交回复
热议问题