Tyler Bell
Tyler Bell

Reputation: 897

Python Deleting All Folders but not files

I am looking to write a piece of python code that deletes all folders and their contents, but does not delete individual files.
For example here are some files and folders contained in a directory (Folder B) along with the script file that does the deleting. How do I delete folderA, folderB,folderC,etc, but leave the files? Thanks

/Folder B 
    file.docx
    fileB.docx
    fileC.docx
    pythonDeleteScript.py
    folderA/
    folderB/
    folderC/
    folderD/

Upvotes: 3

Views: 2627

Answers (1)

justincai
justincai

Reputation: 303

Use os.listdir() to get the contents of the directory, os.path.isdir(path) to see if it is a folder, and if it is, shutil.rmtree(path) to delete the folder and all its content.

Upvotes: 8

Related Questions