Reputation: 1757
I want to remove dataset folder from dataset3 folder. But the following code is not removing dataset.
First I want to check if dataset already exist in dataset then remove dataset.
Can some one please point out my mistake in following code?
for files in os.listdir("dataset3"):
if os.path.exists("dataset"):
os.system("rm -rf "+"dataset")
Upvotes: 85
Views: 136914
Reputation: 424
I think a superior approach, compatible with at least Python 3.5+, is:
with contextlib.suppress(FileNotFoundError):
shutil.rmtree(path)
(You must import contextlib
along with shutil
, both standard modules.)
This solution has the advantages of both the most popular answers:
shutil.rmtree(path, ignore_errors=True)
, there is no separate check for file existence and therefore no race conditionos.path.exists(path)
+ shutil.rmtree(path)
, it will throw an error if the folder was not successfully deleted.Upvotes: 0
Reputation: 123413
Python's os.rmdir()
only works on empty the directories, however shutil.rmtree()
doesn't care (even if there are subdirectories) which makes it very similar to the Linux rm -rf
command.
import os
import shutil
dirpath = os.path.join('dataset3', 'dataset')
if os.path.exists(dirpath) and os.path.isdir(dirpath):
shutil.rmtree(dirpath)
Modern approach
In Python 3.4+ you can do same thing using the pathlib
module to make the code more object-oriented and readable:
from pathlib import Path
import shutil
dirpath = Path('dataset3') / 'dataset'
if dirpath.exists() and dirpath.is_dir():
shutil.rmtree(dirpath)
Upvotes: 140
Reputation: 18819
Better to set ignore_errors
:
import shutil
shutil.rmtree('/folder_name', ignore_errors=True)
This is much more readable, and concise.
Note that it will ignore all errors, not just dir missing errors.
Upvotes: 29
Reputation: 2188
This will do it:
for files in os.listdir('dataset3'):
if files == 'dataset':
os.rmdir(os.path.join(os.getcwd() + 'dataset3', files))
Upvotes: 0
Reputation: 726
try this:
for files in os.listdir("dataset3"):
if files=="dataset":
fn=os.path.join("dataset3", files)
os.system("rm -rf "+fn)
break
You do not need the os.path.exists() because os.listdir() already told you, that it exists.
And if your foldernames are static, you can do it with:
if os.path.exists("dataset3/dataset"):
os.system("rm -rf dataset3/dataset")
or as:
try:
os.system("rm -rf dataset3/dataset")
except:
pass
Upvotes: 1
Reputation: 464
os.remove()
is to remove a file.
os.rmdir()
is to remove an empty directory.
shutil.rmtree()
is to delete a directory and all its contents.
import os
folder = "dataset3/"
# Method 1
for files in os.listdir(folder):
if files == "dataset":
os.remove(folder + "dataset")
# Method 2
if os.path.exists(folder + "dataset"):
os.remove(folder + "dataset")
Upvotes: 27