Delete files and folders in python

How to Delete a File or Folder in Python — Complete Guide

Do you find manually eliminating files or folders tedious? Did you know that the process can be automated with the use of Python? Python is a forceful programming language that empowers you to automate diverse tasks, comprising file and folder deletion. In this article, we will guide you through the step-by-step process of deleting a file or folder in Python.

By writing a few lines of code, you can effortlessly eliminate any extra file or folder on your computer using Python. We will display how to employ the built-in os module to accomplish this task. With our easy-to-follow tutorial, you will save time and optimize your workflow by automating the file deletion procedure.

The many ways that Python offers are:

1. Use os.remove() Function to Remove a File or Folder

The os.remove() function is a built-in Python function that allows you to delete a file or folder from your system. The function takes a single argument, which is the path of the file or folder that you want to delete. If the path is a file, the function will delete the file. If the path is a folder, the function will delete the folder and all of its contents.

To use the os.remove() function to delete a file, you’ll first need to import the os module in your Python script. Once you’ve imported the os module, you can use the os.remove() function to delete the file.

import os file_path = "path/to/file" if os.path.exists(file_path): os.remove(file_path) else: print("The file does not exist.") 

In this example, the os.path.exists(file_path) the function is used to check if the file exists before attempting to delete it. If the file exists, it will be deleted. If the file does not exist, a message will be printed indicating that the file does not exist.

2. Using os.rmdir() Function to Remove

os.rmdir() is another function from the os module in Python that can be used to delete a directory. However, it is important to note that this function can only be used to delete an empty directory.

If the folder contains any files or subfolders, the os.rmdir() function will raise a OSError with the message «Directory not empty». This means that you’ll need to delete the contents of the folder before attempting to remove it using the os.rmdir() function.

Читайте также:  Explode string to array in php

To use the os.rmdir() function to delete an empty folder, you’ll first need to import the os module in your Python script. Once you’ve imported the os module, you can use the os.rmdir() function to delete the folder.

import os directory_path = "path/to/directory" if os.path.exists(directory_path): os.rmdir(directory_path) else: print("The directory does not exist.") 

In this example, the os.path.exists(directory_path) the function is used to check if the directory exists before attempting to delete it. If the directory exists and it is empty, it will be deleted. If the directory does not exist or it is not empty, a message will be printed indicating that the directory does not exist or that it is not empty.

3. Using shutil.rmtree()

The shutil.rmtree() function in Python is used to delete an entire directory tree, including all its subdirectories and files. This is a powerful and versatile method of removing directories and their contents, and it is more efficient than manually deleting each file and folder.

Here’s an example of how you can use shutil.rmtree() to delete a directory:

import shutil directory = "/path/to/directory" shutil.rmtree(directory) 

The rmtree() function takes a single argument, which is the path to the directory you want to remove. It will recursively remove all subdirectories and files in the specified directory, and then remove the directory itself.

It’s important to be cautious when using rmtree() because it can permanently delete files, and there’s no way to undo the operation. Make sure you understand the consequences of using this function and always double-check the path to the directory you want to remove to avoid accidentally deleting important files.

You can also add error handling to the code to make it more robust. For example:

import shutil import os directory = "/path/to/directory" if os.path.exists(directory): shutil.rmtree(directory) else: print("The directory does not exist.") 

4. Using pathlib.Path(empty_dir_path).rmdir()

This particular module, which is part of the standard library, provides an object-oriented and high-level interface for directory and file manipulation.

To execute the process of directory removal, one must provide a string which denotes the file path of the directory that is to be erased. The pathlib.Path constructor will then create a Path object, which functions as a representation of the directory path in the file system. The rmdir() method is then employed to delete the directory represented by the Path object.

It is crucial to acknowledge that the directory in question must be void of any contents for the rmdir() method to work. In the event that the directory has contents, a FileNotFoundError exception will be triggered. Should one desire to delete a directory that is not empty, either the shutil library or custom code must be utilized to eliminate the directory’s contents before the rmdir() method is called.

Below is an example that showcases how pathlib.Path(empty_dir_path).rmdir() may be utilized in the act of deleting a directory.

import pathlib empty_dir_path = "/path/to/empty/directory" pathlib.Path(empty_dir_path).rmdir() 

This will delete the directory at the specified path, assuming it’s empty.

Читайте также:  Java классы и объекты примеры

Conclusion

In conclusion, deleting files and folders is an essential task when it comes to programming in Python. With the help of the os and shutil modules, you can easily delete files and folders in your Python scripts. It’s crucial to note that you should always exercise caution when deleting files and ensure that you have taken the necessary backups before proceeding.

Источник

Python Delete File – How to Remove Files and Folders

Kolade Chris

Kolade Chris

Python Delete File – How to Remove Files and Folders

Many programming languages have built-in functionalities for working with files and folders. As a rich programming language with many exciting functionalities built into it, Python is not an exception to that.

Python has the OS and Pathlib modules with which you can create files and folders, edit files and folders, read the content of a file, and delete files and folders.

In this article, I’ll show you how to delete files and folders with the OS module.

What We’ll Cover

How to Delete Files with the OS Module

To delete any file with the OS module, you can use it’s remove() method. You then need to specify the path to the particular file inside the remove() method. But first, you need to bring in the OS module by importing it:

import os os.remove('path-to-file') 

This code removes the file questions.py in the current folder:

import os os.remove('questions.py') 

If the file is inside another folder, you need to specify the full path including the file name, not just the file name:

import os os.remove('folder/filename.extension') 

The code below shows how I removed the file faq.txt inside the textFiles folder:

import os os.remove('textFiles/faq.txt') 

To make things better, you can check if the file exists first before removing it:

import os # Extract the file path to a variable file_path = 'textFiles/faq.txt' #check if the file exists with path.exists() if os.path.exists(file_path): os.remove('textFiles/faq.txt') print('file deleted') else: print("File does not exists") 

You can also use try..except for the same purpose:

import os try: os.remove('textFiles/faq.txt') print('file deleted') except: print("File doesn't exist") 

How to Delete Files with the Pathlib Module

The pathlib module is a module in Python’s standard library that provides you with an object-oriented approach to working with file system paths. You can also use it to work with files.

The pathlib module has an unlink() method you can use to remove a file. You need to get the path to the file with pathlib.Path() , then call the unlink() method on the file path:

import pathlib # get the file path try: file_path = pathlib.Path('textFiles/questions.txt') file_path.unlink() print('file deleted') except: print("File doesn't exist") 

How to Delete Empty Folders with the OS Module

The OS module provides a rmdir() method with which you can delete a folder.

But the way you delete an empty folder is not the same way you delete a folder with files or subfolders in it. Let’s see how you can delete empty folders first.

Читайте также:  Разделить массив запятыми javascript

Here’s how I deleted an empty client folder:

import os try: os.rmdir('client') print('Folder deleted') except: print("Folder doesn't exist") 

If you attempt to delete a folder that has files or subfolders inside it, you’ll get the Directory not empty error :

import os os.rmdir('textFiles') # OSError: [Errno 66] Directory not empty: 'textFiles' 

How to Delete Empty Folders with the Pathlib Module

With the pathlib module, you can extract the path of the folder you want to delete into a variable and call rmdir() on that variable:

import pathlib # get the folder path try: folder_path = pathlib.Path('docs') folder_path.rmdir() print('Folder deleted') except: print("Folder doesn't exist") 

To delete a folder that has subfolders and files in it, you have to delete all the files first, then call os.rmdir() or path.rmdir() on the now empty folder. But instead of doing that, you can use the shutil module. I will show you this soon.

How to Delete a Non-Empty with the shutil Module

The shutil module has a rmtree() method you can use to remove a folder and its content – even if it contains multiple files and subfolders.

The first thing you need to do is to extract the path to the folder into a variable, then call rmtree() on that variable.

Here’s how I deleted a folder named subTexts inside the textFiles folder:

import shutil try: folder_path = 'textFiles/subTexts' shutil.rmtree(folder_path) print('Folder and its content removed') except: print('Folder not deleted') 

And here’s how I removed the whole textFiles folder (it has several files and a subfolder):

import shutil try: folder_path = 'textFiles' shutil.rmtree(folder_path) print('Folder and its content removed') # Folder and its content removed except: print('Folder not deleted') 

Conclusion

This article took you through how to remove a file and empty folder with the os and pathlib modules of Python. Because you might also need to remove non-empty folders too, we took a look at how you can do it with the shutil module.

If you found the article helpful, don’t hesitate to share it with your friends and family.

Kolade Chris

Kolade Chris

Web developer and technical writer focusing on frontend technologies. I also dabble in a lot of other technologies.

If you read this far, tweet to the author to show them you care. Tweet a thanks

Learn to code for free. freeCodeCamp’s open source curriculum has helped more than 40,000 people get jobs as developers. Get started

freeCodeCamp is a donor-supported tax-exempt 501(c)(3) charity organization (United States Federal Tax Identification Number: 82-0779546)

Our mission: to help people learn to code for free. We accomplish this by creating thousands of videos, articles, and interactive coding lessons — all freely available to the public. We also have thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services, and staff.

Источник

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