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

前端 未结 6 469
没有蜡笔的小新
没有蜡笔的小新 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 16:54

    Just say

    dir = 'path_to_my_folder'
    if not os.path.exists(dir): # if the directory does not exist
        os.makedirs(dir) # make the directory
    else: # the directory exists
        #removes all files in a folder
        for the_file in os.listdir(dir):
            file_path = os.path.join(dir, the_file)
            try:
                if os.path.isfile(file_path):
                    os.unlink(file_path) # unlink (delete) the file
            except Exception, e:
                print e
    

提交回复
热议问题