Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to remove a directory? Is os.removedirs and os.rmdir only used to delete empty directories? [duplicate]

Tags:

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

like image 712
Mustafa Avatar asked Feb 20 '18 19:02

Mustafa


People also ask

Can you use the rmdir command to delete a directory that is not empty?

rmdir command – Delete directory only if it is empty. rm command – Remove directory and all files even if it is NOT empty by passing the -r to the rm to remove a directory that is not empty.

What will happen if OS remove () is used to remove an empty directory?

Python os Error Handling remove() to remove a directory, an error will be returned. If we use os. rmdir() to remove a directory that contains files, an error will be returned.

What is the command that can only be used to delete an empty directories?

Using rmdir command rmdir command is used to delete empty directories. It only deletes the empty directories, so, if the directory is not empty it will show an error.


1 Answers

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.

like image 114
Moinuddin Quadri Avatar answered Sep 17 '22 19:09

Moinuddin Quadri