Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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) 

The folder will be used by a program to write text files into that folder. But I want to start with a brand new, empty folder next time my program opens up.

Is there a way to overwrite the folder (and create a new one, with the same name) if it already exists?

like image 597
Shankar Kumar Avatar asked Jul 26 '12 00:07

Shankar Kumar


People also ask

Does makedirs overwrite?

Overwrite Directory Even ExistBy default, the makedirs() method will not overwrite if the provided directory exists currently. This is set with the is_exist parameter which is set as False by default. We can set this parameter as True in order to overwrite the existing directory.

How do I overwrite an existing directory in Python?

So that we may need to overwrite the existing destination file with the source file. The shutil. move() method is used to move a file or directory from one place to another. If there is an existing directory or file in the destination which will be checked using os.

How do you overwrite a file in Python?

To overwrite a file, to write new content into a file, we have to open our file in “w” mode, which is the write mode. It will delete the existing content from a file first; then, we can write new content and save it. We have a new file with the name “myFile.

How do you delete a directory in Python?

Deleting file/dir using the os.rmdir() method in Python is used to remove or delete an empty directory. OSError will be raised if the specified path is not an empty directory.


2 Answers

import os import shutil  dir = 'path_to_my_folder' if os.path.exists(dir):     shutil.rmtree(dir) os.makedirs(dir) 
like image 196
inspectorG4dget Avatar answered Sep 20 '22 16:09

inspectorG4dget


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!

like image 40
cybertextron Avatar answered Sep 22 '22 16:09

cybertextron