Python Delete File – Step-by-Step Guide
Tags: python, programming, codenewbie, tutorial
Published: 2021-09-14 03:53:49

---
title: Python Delete File – Step-by-Step Guide
published: true
date: 2021-09-13 13:11:08 UTC
tags: #python #programming #codenewbie #tutorial
canonical_url: https://itsmycode.com/python-delete-file-step-by-step-guide/
---

ItsMyCode |

Python has several built-in modules that allow you to delete a file or remove directories.

This tutorial is a step-by-step guide to remove a file or directory using 3 different methods.

1. **Using `os `module**
2. **Using `shutil `module**
3. **Using `pathlib `module**

## Methods to Delete Files in Python

Let’s look at each of these modules and the functions we can utilize to delete a directory or files.

## Method 1 – Using os Module

The **`os `** module is a built-in utility available in both Python 2 and 3 versions, and it provides functions to interact easily with the operating system.

### **Delete a file**

**`os.remove()`** is used to remove or delete a file in Python. This method cannot remove a directory, and if you try giving a directory as a path, it throws an  **_OSError_**.

**_Syntax – _os.remove(path, \*, dir\_fd = None)**

**Parameters:**  It takes a file path as an input parameter, and the path can be of a type string. The function does not return anything.

```python 
# Import os module
import os

filePath='/Projects/Tryouts/test/python.txt'
# check whethere the provided filepath exists and if its of file type
if os.path.isfile(filePath):
    # delete the file using remove function
    os.remove(filePath)
    print("Successfully deleted a file")
else:    
    print("File doesn't exists!")
```

**Output**

```python 
Successfully deleted a file
```

**Note –** If you do not check for **`isFile `** or specify an invalid path to the **`os.remove() `**method, Python will throw a **`FileNotFoundError `** as shown below.

```python 
Traceback (most recent call last):
  File "c:\Projects\Tryouts\main.py", line 3, in <module>
    os.remove(filePath)
FileNotFoundError: [WinError 2] The system cannot find the file specified: '/Projects/Tryouts/test/path_does_not_exsist.txt'
```

### **Delete a directory**

The os module has an **`os.rmdir()`** method to  **remove or delete an empty directory. ** If the directory does not exist or is found not empty, you will get an  **_OSError._**

_**Syntax: os.rmdir(path, \*, dir\_fd = None)**_

**Parameters:**  It takes a folder path as an input parameter, and the path can be of a type string. The function does not return anything.

Note – If you do not check for `isdir `or specify an invalid path to the **`os.rmdir()` **method, Python will throw a **`FileNotFoundError `** as shown below.

```python 
# Import os module
import os

folderPath='/Projects/Tryouts/test/'
# check whethere the provided folder path exists and if its of directory type
if os.path.isdir(folderPath):
    # delete the folder using rmdir function
    os.rmdir(folderPath)
    print("Successfully deleted a folder")
else:    
    print("Folder doesn't exists!")
```

**Output**

```python 
Successfully deleted a folder
```

## Method 2 – Using shutil module

The drawback in the **`os `** module was you cannot delete an entire directory with contents inside it. If you want to delete a directory and remove all the files inside it recursively, you should use **`shutil.rmtree()`** method.

**_Syntax: shutil.rmtree(path, ignore\_errors=False, onerror=None)_**

Parameters:

- **_path_** – A path like an object representing a folder path
- **_ignore\_errors_** – If set to true, any error that occurs while removing will be ignored. The default value is false.
- **_oneerror_:**  If _`ignore_errors `_are false or omitted, such errors are handled by calling a handler specified by  **onerror**.

```python 
# Import os module
import shutil

# Directory that needs to be deleted. Removes all the files and folders inside the path
folderpath='/Projects/Tryouts/test/'
shutil.rmtree(folderpath)

```

## Method 3 – Using pathlib module

If you are using the Python 3.4+ version, you could leverage  **the `pathlib `** module, which comes as a built-in module. This module offers classes representing filesystem paths with semantics appropriate for different operating systems.

There are 2 main functions over here –

### **Remove a file**

**`pathlib `** has a method called **`Path.unlink()`** which removes a file or symoblic link.

**_Syntax – Path.unlink(missing\_ok=False)_**

If  **`missing_ok `** is false (the default), **[FileNotFoundError](https://docs.python.org/3/library/exceptions.html#FileNotFoundError) **is raised if the path does not exist.

```python 
# Import os module
import pathlib

# removes the current file path or symbolic link
file_to_remove= pathlib.Path('/Projects/Tryouts/test/python.txt')
file_to_remove.unlink()

```

### **Remove a directory**

**`pathlib `** has a method called **`Path.rmdir()`** which removes the specified directory. The directory must be empty else it will raise an  **OSError.**

```python 
# Import os module
import pathlib

# removes the current directory if its empty
folder_to_remove= pathlib.Path('/Projects/Tryouts/test/')
folder_to_remove.rmdir()

```

The post [Python Delete File – Step-by-Step Guide](https://itsmycode.com/python-delete-file-step-by-step-guide/) appeared first on [ItsMyCode](https://itsmycode.com).