How can I check if a folder exists and delete it?
I want to delete dataset folder from dataset3 folder. But the following code does not delete the dataset. I first want to check if the dataset already exists in the dataset and then delete the dataset.
Can anyone please point out my error in the following code?
for files in os.listdir("dataset3"):
if os.path.exists("dataset"):
os.system("rm -rf "+"dataset")
source to share
os.remove()
- delete a file.
os.rmdir()
- delete an empty directory.
shutil.rmtree()
- delete the 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")
source to share
os.rmdir()
will only work if the directory is empty, however the following does not matter (even if there are subdirectories). It's also more portable than usage os.system()
and commands rm
.
import shutil
import os
dirpath = os.path.join('dataset3', 'dataset')
if os.path.exists(dirpath) and os.path.isdir(dirpath):
shutil.rmtree(dirpath)
source to share
try this:
for files in os.listdir("dataset3"):
if files=="dataset":
fn=os.path.join("dataset3", files)
os.system("rm -rf "+fn)
break
You don't need os.path.exists () because os.listdir () already told you that it exists.
And if your names in the folder are static, you can do it with
if os.path.exists("dataset3/dataset"):
os.system("rm -rf dataset3/dataset")
or how:
try:
os.system("rm -rf dataset3/dataset")
except:
pass
source to share