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")

      

+3


source to share


4 answers


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")

      

+6


source


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)

      

+6


source


This will be done:

for files in os.listdir('dataset3'):
     if files == 'dataset':
         os.rmdir(os.path.join(os.getcwd() + 'dataset3', files))

      

0


source


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

      

0


source







All Articles