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!