5 Ways to Delete File in Python

Python delete file methods are used considering that we frequently need to manipulate files. Deleting files in all programming languages, including Python, is one of the basic operations that often give developers headaches due to their “dangerous” effects.

Removing files without a good understanding of built-in functions, methods, and libraries can create a lot of problems.

As so, you can delete entire directories, files, and important data. Therefore, it is necessary to know all the methods and their actions to avoid such things.

The easiest way to delete a file in Python is to use:
os.remove(file_path)

Import the os module built into Python, then use the remove, to which we pass the path to the file we want to delete.

In addition to this method, there are several ways to delete a file, in this blog post we will go through 5 methods:

  • os.remove
  • os.rmdir
  • shutil.rmtree
  • pathlib.Path.unlink
  • pathlib.Path.rmdir
os.removeos.rmdirshutil.rmtreepathlib.Path.unlinkpathlib.Path.rmdir
Path to fileSuccessNotADirectoryErrorNotADirectoryErrorSuccessNotADirectoryError
Path to an empty directoryIsADirectoryErrorSuccessSuccessIsADirectoryErrorSuccess
Path to non-empty directoryIsADirectoryErrorOSErrorSuccessIsADirectoryErrorOSError
Nonexistent pathFileNotFoundErrorFileNotFoundErrorFileNotFoundErrorFileNotFoundErrorFileNotFoundError
Possible errors:

  • FileNotFoundError
  • IsADirectoryError
  • NotADirectoryError
  • OSError
  • We will first process the methods that belong to the Python os module.

    Delete file in Python using os module methods

    The Python os module is an operating system interface for using os functionalities. You can manipulate files, paths, directories, and much more.

    We will focus directly on the methods by which we can delete a file or an entire directory.

    Remove method

    os.remove(path, *, dir_fd=None)

    • path
      • file path
    • dir_fd
      • paths relative to directory descriptors
      • default is None
      • if not None, the path is relative to a given directory

    Let’s dive into examples!

    Example 1.

    import os
    
    os.remove('file.txt')
    

    If the path does not exist: FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'

    If we try to delete a directory: IsADirectoryError: [Errno 21] Is a directory: 'dir'

    Rmdir method

    os.rmdir(path, *, dir_fd=None)

    • path
      • file path
    • dir_fd
      • paths relative to directory descriptors
      • default is None
      • if not None, the path is relative to a given directory

    Example 1.

    import os
    
    os.rmdir('dir')
    

    os.rmdir returns None if successfully deleted directory.

    Unlike the remove method, rmdir cannot delete files, so if the directory is not empty it will come to OSError: [Errno 39] Directory not empty: 'dir'

    If we try to delete a file: NotADirectoryError: [Errno 20] Not a directory: 'file.txt'.

    If the directory does not exist: FileNotFoundError: [Errno 2] No such file or directory: 'dir'.

    Official os documentation

    Delete File in Python using shutil module method

    Shutil module works and it’s built at a higher level than the os module. Each shutil function call can represent multiple calls at a lower level. Shutil module is used for file management.

    Rmtree method

    Removes entire directory tree.

    shutil.rmtree(path, ignore_errors=False, onerror=None)

    • path
      • file path
    • ignore_errors
      • defaults False
      • if True error will be ignored
    • oneerror
      • defaults None
      • handler for errors
        • function that gets 3 arguments ( function, path, and excinfo )

    Example 1.

    import shutil
    
    shutil.rmtree('dir')
    

    Rmtree receives a path to the directory, but unlike rmdir, it will delete a directory regardless of whether it is empty or full.

    If the path does not exist: FileNotFoundError: [Errno 2] No such file or directory: 'dir'

    If we try to delete the file: NotADirectoryError: [Errno 20] Not a directory: 'file'

    Example 2.

    import os
    import shutil
    import stat
    
    def remove_file(func, path, _):
        """If file can’t be deleted, change file permissions and call function once again"""
    
        if not os.access(path, os.W_OK):
           os.chmod(path, stat.S_IWUSR)
           func(path)
    
    
    shutil.rmtree('file', onerror=remove_file)
    

    Here is shown usage of oneerror argument where we pass remove_file function.

    We check if we have Write permissions, if not we give it to the user and call the function once again to delete the file.

    For more advanced usages check official shutil documentation

    Delete File in Python using pathlib module methods

    Pathlib allows file management on different operating systems.

    Several classes represent Paths on different operating systems. Here we will focus on the most used class of this module and that is the Path class.

    Unlink method

    Path.unlink(missing_ok=False)

    • missing _ok
      • defaults False
      • FileNotFoundError will appear if the path does not exist and the flag is set to True

    Example 1.

    from pathlib import Path
    
    path = Path('file.txt')
    path.unlink()
    

    If the path does not exist: FileNotFoundError: [Errno 2] No such file or directory: 'file.txt'. This is avoided by setting the missing_ok=True flag, in which case the error is ignored.

    If we try to delete the directory: IsADirectoryError: [Errno 21] Is a directory: 'dir' error (regardless of the flag).

    Rmdir method

    Path.rmdir()

    Doesn’t take any arguments, deletes the given path.

    Example 1.

    from pathlib import Path
    
    path = Path('dir')
    path.rmdir()
    

    Similar to the previous example, over the object we call the rmdir method. But like other methods, we come to similar results.

    If a directory is not empty: OSError: [Errno 39] Directory not empty: 'dir'.

    If we try to delete the file: NotADirectoryError: [Errno 20] Not a directory: 'file.txt'.

    Official pathlib documentation

    Tips for deleting files in Python

    • Before deleting, check if the file exists (to prevent possible errors)
      • os.path.isfile(file_path)
    • Use carefully shutil.rmtree
    • To recursively delete directories, use os.removedirs(dir)
    • Deleting files on Windows and Linux is not the same thing !!
    • os.remove equals os.unlink