Reputation:
Is it possible to delete all folders inside a folder without using a specific path?, Here i am moving the contents of the file then after that i want to delete if it is a dir
import os, zipfile
import shutil
import os
from os import path
dir_name = 'C:\\Users\\Guest\\Desktop\\OJT\\samples'
destination = 'C:\\Users\\Guest\\Desktop\\OJT\\scanner\\test'
for path, subdirs, files in os.walk(destination):
for name in files:
filename = os.path.join(path, name)
shutil.copy2(filename, destination)
Upvotes: 4
Views: 782
Reputation: 3447
Yes it is, Use shutil's rmtree
method.
import shutil
shutil.rmtree('directory') # the directory you want to remove
os.listdir()
You can also use os.rmdir
but that won't work if there is any content in it.
If you want to check if that specific path is a directory then you can use os.path.isdir
then run rmtree
if that returns TRUE
And incase you want to keep the root folder intact then you could walk
that directory and calling rmtree
on each item.
Upvotes: 7
Reputation: 3526
If Vineeth's
answer is not suitable for your case, you could you subprocess
module to run os
specific commands like below
import subprocess
subprocess.call('rm -rf /path/of/the/dirctory/*', shell=True)
The above command is linux
specific, you could use windows counterpart of the same command above.
Note - Here shell=True
will expand *
into files/folders.
Also, note Vineeth's
answer is os
independent, and above will be os
specific. Be cautious.
P.S. - You can also run powershell
commands using subprocess
module.
Upvotes: 1
Reputation: 26315
As suggested by @Vineeth Sai earlier, If you want to delete all sub directories in a directory, just loop through each file with os.listdir()
and if the file is a directory, apply shutil.rmtree()
:
from os import listdir
from os.path import abspath
from os.path import isdir
from os.path import join
from shutil import rmtree
path = 'YOUR PATH HERE'
for file in listdir(path):
full_path = join(abspath(path), file)
if isdir(full_path):
rmtree(full_path)
The above also uses os.isdir()
to check if a file is a directory.
Upvotes: 1