Is there a way to delete a folder in python if it does not contain any files? I can do the foll:
os.rmdir() will remove an empty directory.
shutil.rmtree() will delete a directory and all its contents.
If the folder has empty sub-folders, it should be deleted too
os.removedirs(path)
Remove directories recursively. Works like rmdir() except that, if the
leaf directory is successfully removed, removedirs() tries to
successively remove every parent directory mentioned in path until an
error is raised (which is ignored, because it generally means that a
parent directory is not empty).
e.g.
import os
if not os.listdir(dir):
os.removedirs(dir)
See more details from os.removedirs.
Hope this helps.
Related
I want to write a shell script that aims to traverse a root directory C:\xyz and find whether a sub directory "Demo" is available in any directories or not. If "Demo" is available & not empty, print 'OK', if "Demo" directory is empty, print 'NOT_OK'.
(Assuming you want a Python script to be executed in the terminal and not an actual shell script)
You can use os.walk to recursively list all the files and subdirectories in a given directory. This creates a generator with items in the form ("path/from/root", [directories], [files]) which you can then check whether any of those (a) is the desired Demo directory, and (b) is not empty.
import os
exists_and_not_empty = any(path.endswith("/Demo") and (dirs or files)
for (path, dirs, files) in os.walk(root_dir))
This will also return True if the target directory is contained directly in the root directory, or if it is nested deeper in subdirectories of subdirectories. Not entirely clear from your question if this is intended, or if the target directory has to be in a direct subdirectory of the root directory.
To see if there are any directories in folder xyz that contains another directory named 'Demo', and if so, whether or not 'Demo' is empty, you can use the glob module
from glob import glob
if glob("C:\\xyz\\**\\Demo\\*", recursive=True):
print("OK")
else:
print("NOT_OK")
This question already has answers here:
How can I delete a file or folder in Python?
(15 answers)
Closed 5 years ago.
Whenever I try to use them to remove dirs with things in them I get this error message
import os
os.chdir('/Users/mustafa/Desktop')
os.makedirs('new-file/sub-file')
os.removedirs('new-file')
"/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/os.py", line 170, in removedirs
rmdir(name)
OSError: [Errno 66] Directory not empty: 'new-file'
However I think I saw people using those commands to delete dirs that weren't empty, so what am I doing wrong? Thanks
You should be using shutil.rmtree to recursively delete directory:
import shutil
shutil.rmtree('/path/to/your/dir/')
Answer to your question:
Is os.removedirs and os.rmdir only used to delete empty directories?
Yes, they can only be used to delete empty directories.
Below is the description from official Python document which clearly stats that.
os.rmdir(path, *, dir_fd=None)
Remove (delete) the directory path. Only works when the directory is empty, otherwise, OSError is raised. In order to remove whole directory trees, shutil.rmtree() can be used.
os.removedirs(name)
Remove directories recursively. Works like rmdir() except that, if the leaf directory is successfully removed, removedirs() tries to successively remove every parent directory mentioned in path until an error is raised (which is ignored, because it generally means that a parent directory is not empty). For example, os.removedirs('foo/bar/baz') will first remove the directory 'foo/bar/baz', and then remove 'foo/bar' and 'foo' if they are empty. Raises OSError if the leaf directory could not be successfully removed.
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/
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.
I need to make a script that will iterate through all the directories inside a directory. It should go into each directory, get its name and save it to a variable and comes back out, and then loops.
for dir in os.walk(exDir):
path = dir
os.chdir(path)
source = #dir trimmed to anything after the last /
os.chdir("..")
loops
It needs to go into the directory to do other things not mentioned above. I've only just started Python and have been stuck on this problem for the last day or so.
For each iteration of your for loop, dir is a tuple of format (filepath, subdirectories, files). As such dir[0] will give you the filepath.
It sounds like you just want to os.chdir for each folder recursively in exDir in which case the following will work:
for dir in os.walk(exDir):
os.chdir(dir[0])
...
We just switched over our storage server to a new file system. The old file system allowed users to name folders with a period or space at the end. The new system considers this an illegal character. How can I write a python script to recursively loop through all directories and rename and folder that has a period or space at the end?
Use os.walk. Give it a root directory path and it will recursively iterate over it. Do something like
for root, dirs, files in os.walk('root path'):
for dir in dirs:
if dir.endswith(' ') or dir.endswith('.'):
os.rename(...)
EDIT:
We should actually rename the leaf directories first - here is the workaround:
alldirs = []
for root, dirs, files in os.walk('root path'):
for dir in dirs:
alldirs.append(os.path.join(root, dir))
# the following two lines make sure that leaf directories are renamed first
alldirs.sort()
alldirs.reverse()
for dir in alldirs:
if ...:
os.rename(...)
You can use os.listdir to list the folders and files on some path. This returns a list that you can iterate through. For each list entry, use os.path.join to combine the file/folder name with the parent path and then use os.path.isdir to check if it is a folder. If it is a folder then check the last character's validity and, if it is invalid, change the folder name using os.rename. Once the folder name has been corrected, you can repeat the whole process with that folder's full path as the base path. I would put the whole process into a recursive function.