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 osmodule
  2. Using shutilmodule
  3. Using pathlibmodule

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.

# 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

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.

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 isdiror specify an invalid path to the os.rmdir() *method, Python will throw a *FileNotFoundError as shown below.

# 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

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.
# 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 **is raised if the path does not exist.

# 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.

# Import os module
import pathlib

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

31