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?
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.
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.
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.
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.
import os import shutil dir = 'path_to_my_folder' if os.path.exists(dir): shutil.rmtree(dir) os.makedirs(dir)
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With