Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
103 views
in Technique[技术] by (71.8m points)

python - How to check existence of a folder and then remove it?

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")
question from:https://stackoverflow.com/questions/43765117/how-to-check-existence-of-a-folder-and-then-remove-it

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

os.rmdir() only works if the directory is empty, however shutil.rmtree() doesn't care (even if there are subdirectories). It's also more portable than using the rm command via os.system().

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...