How to overwrite a folder if it already exists when creating it with makedirs?

前端 未结 6 492
没有蜡笔的小新
没有蜡笔的小新 2020-12-23 16:20

The following code allows me to create a directory if it does not already exist.

dir = \'path_to_my_folder\'
if not os.path.exists(dir):
    os.makedirs(dir)         


        
6条回答
  •  星月不相逢
    2020-12-23 17:10

    import os
    import shutil
    
    path = 'path_to_my_folder'
    if not os.path.exists(path):
        os.makedirs(path)
    else:
        shutil.rmtree(path)           # Removes all the subdirectories!
        os.makedirs(path)
    

    How about that? Take a look at shutil's Python library!

提交回复
热议问题