Home » Programming » Python » Python Delete File Folder Directory

How to Delete a File/Folder/Directory in Python

This article will show you the various ways to delete files and directories in the Python programming language.

To Avoid Errors, First Check if a File or Folder Exists

To avoid errors when deleting a file, you can first check whether the file exists.

You can also check whether Python is able to modify a directory.

Deleting a File

When a file has been confirmed to exist at a certain path, it can be deleted with the os.remove() function, which is part of the built-in Python os library which interacts with the host operating system and performs file operations:

# Import the os library
import os

# Delete file
os.remove("path/to/myfile.txt")

Removing a Directory

The os library also includes the rmdir() function for removing directories:

# Import the os library
import os

# Delete directory
os.rmdir("path/to/directory")

Only empty directories can be removed with os.rmdir() – an error will be thrown if there are any files present in the directory attempted being removed.

Removing a Populated Directory

Directories with files present in them can be removed using the shutil.rmtree() function, which is part of the built-in Python shutil library, which performs higher level file operations:

# Import the shutil library
import shutil

# Delete populated directory
shutil.rmtree('path/to/populated/directory')

Using Path Objects

Path objects created using the pathlib library represent files and directories in an object-oriented manner in your Python code.

Path objects contain instances for removing the files or directories at a specified path:

# Import the pathlib library
import pathlib

# Create a path object for a folder on disk
myFolder = pathlib.Path('path/to/folder')

# Delete the folder on disk
myFolder.rmdir()

# Create a path object for a file on disk
myFile = pathlib.Path('path/to/file.txt')

# Delete the file on disk
myFile.unlink()

Again, only empty directories can be removed using this method.

Be Careful!

The above functions do not prompt for confirmation or send files to the the trash for recovery – when Python deletes a file, it is deleted.

Be careful that you specify the correct paths so that you don’t accidentally delete something important!

SHARE:
Photo of author
Author
I'm Brad, and I'm nearing 20 years of experience with Linux. I've worked in just about every IT role there is before taking the leap into software development. Currently, I'm building desktop and web-based solutions with NodeJS and PHP hosted on Linux infrastructure. Visit my blog or find me on Twitter to see what I'm up to.

Leave a Comment