Reputation: 159
I have some code that if a certain folder exists, I want to remove it, and if the folder does not exist, I want to create that folder.
Below is my code:
import os
def build_file_structure():
if os.path.exists('new data'):
os.remove('new data')
else:
os.mkdir('new data')
source_dir = ''
dst = 'new data'
return source_dir, dst
if __name__ == "__main__":
source_dir, dst = build_file_structure()
The code works fine when there is no folder "newdata", but when the "newdata" folder exists prior to running I receive this error:
os.remove('new data')
PermissionError: [WinError 5] Access is denied: 'new data'
Upvotes: 1
Views: 5706
Reputation: 9575
Use os.rmdir
(remove directory) in order to remove folders.
os.rmdir('new data')
Upvotes: 1
Reputation: 2210
You could try using any one of the below
Using shell util library
import shutil
shutil.rmtree(dir_path)
Traditional os
module
os.rmdir(dir_path)
Upvotes: 3