Python delete folder with files

How To Use Python os.remove Method To Remove Files And Folders

In Python, you can use the os.remove method to remove files and folders, but sometimes it may resulting in some errors, this is because you do not master how to use the os.remove method correctly. This article will introduce how to use the python os.remove method correctly to avoid errors.

1. Python os.remove Method Overview.

  1. Grammar: os.remove(path).
  2. Parameter: Path — file path to remove.
  3. Return value: The method does not return value.

2. How To Use It To Avoid Errors.

# The test folder is an empty folder, from the folder permission, we can see that everyone can remove the below folder. drwxrwxrwx 2 songzhao staff 64 Feb 25 09:33 test # But when we remove it with the python os.remove method, it will through an Operation not permitted error. >>> import os >>> >>> >>> os.remove('./test') Traceback (most recent call last): File "", line 1, in PermissionError: [Errno 1] Operation not permitted: './test' # os.remove method can remove a file successfully. >>> os.remove('./test/test.php') # Now the test folder is empty, but when you remove it with os.remove method, it will still throw Operation not permitted error. >>> os.remove('./test') Traceback (most recent call last): File "", line 1, in PermissionError: [Errno 1] Operation not permitted: './test'

3. How To Remove A Folder With Files Inside In Python.

>>> import shutil >>> >>> shutil.rmtree('./test')
>>> import shutil >>> >>> >>> shutil.rmtree('./test/test.py') Traceback (most recent call last): File "", line 1, in File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 513, in rmtree return _rmtree_unsafe(path, onerror) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 374, in _rmtree_unsafe onerror(os.scandir, path, sys.exc_info()) File "/Library/Frameworks/Python.framework/Versions/3.7/lib/python3.7/shutil.py", line 371, in _rmtree_unsafe with os.scandir(path) as scandir_it: NotADirectoryError: [Errno 20] Not a directory: './test/test.py'

4. Python os.remove Method Example.

>>> import os, sys >>> # Get current python execution path. >>> curr_path = os.getcwd() >>> >>> print(curr_path) /Users/songzhao >>> >>> new_path = curr_path + '/test' >>> >>> print(new_path) /Users/songzhao/test >>> >>> # List files in the new directory. >>> os.listdir(new_path) ['test.py'] >>> # Use os.remove to remove a directory, it will throw an error. >>> os.remove(new_path) Traceback (most recent call last): File "", line 1, in PermissionError: [Errno 1] Operation not permitted: '/Users/songzhao/test' >>> # Use os.remove to remove a file will be successful. >>> os.remove(new_path+'/test.py') >>> >>> # After the file has been removed, the directory is empty. >>> os.listdir(new_path) []

Источник

Читайте также:  Javascript if key exists in object

How To Delete a Directory In Python

python remove directory

We’ll learn how to delete a folder or directory in Python in this post. We’ll delete an empty folder as well as delete a directory and all files from it using shutil module.

Python shutil module

shutil module is a powerful module in Python that can be used for high-level file operations. Some of the operations that can be performed using shutil module are copying, moving and deleting files and directories. We’ll use os module along with shutil to perform these operations.

Deleting an empty directory or folder in Python is simple by using the os module.

  • os.rmdir : Deletes a folder.
  • shutil.rmtree : Deletes a directory and all its contents.
  • pathlib.Path(empty_dir_path).rmdir() : The pathlib module was added in Python 3.4. This method is used to unlink and delete the empty folder.

Delete an Empty folder OR Directory

It’s important that the folder we’re going to delete is empty. A warning will appear, stating that the folder is not empty. We can determine the folder is empty or not using os.listdir() method.

folder_path = r"D:\python-test\logs" if os.path.exists(folder_path): # checking whether the folder is empty or not if len(os.listdir(folder_path)) == 0: # removing the file using the os.rmdir() method os.rmdir(folder_path) print("Deleted '%s' directory successfully" % empty_dir) else: # messaging saying folder not empty print("Directory '%s' is not empty" % empty_dir) else: print("The directory '%s' not found" % empty_dir)

Error Handling while deleting a directory

We can also handle errors on the deletion of the directory using os.rmdir() method.

try: os.rmdir(path) print("Directory '% s' has been removed successfully" % directory) except OSError as error: print(error) print("Directory '% s' can not be removed" % directory)
[WinError 145] The directory is not empty: 'D:/python-test/logs' Directory 'logs' can not be removed

Delete a folder and all its subfolders recursively

The shutil module in Python allows you to conduct high-level operations on a file or a group of files. We’ll use shutil module’s .rmtree() method to remove delete a folder and all of the contents contained within it.

The .rmtree() function deletes the specified folder and all its subfolders recursively.

  • path – The path of the directory to delete. The symbolic links to a directory are not acceptable.
  • ignore_errors – If this flag is set to true, then the errors due to failed removals will be ignored.
  • onerror: If ignore_errors is false or omitted, such errors are handled by calling a handler specified by onerror.
Читайте также:  Python json to string human

Example: Delete directory Using rmtree()

import shutil # Deleting an non-empty folder dir_path = r"D:\python-test\logs" shutil.rmtree(dir_path, ignore_errors=True) print("Deleted '%s' directory successfully" % dir_path)
Deleted 'D:\python-test\logs' directory successfully

You can also delete an empty directory by using the pathlib module’s rmdir() method. You first have to set the path for the directory, and then you call the rmdir() method on that path.

empty_dir_path: The empty directory path.

This method does not return any value.

Delete an empty directory

The pathlib module’s rmdir() method can also be used to remove or delete an empty directory.

import pathlib # Deleting an empty folder empty_dir = r"D:\python-test\logs" path = pathlib.Path(empty_dir) path.rmdir() print("Deleted '%s' directory successfully" % empty_dir)
Deleted 'D:\python-test\logs' directory successfully

Источник

Оцените статью