From the course: Python: Working with Files

Unlock the full course today

Join today to access over 24,900 courses taught by industry experts.

Delete files with Python

Delete files with Python - Python Tutorial

From the course: Python: Working with Files

Delete files with Python

- [Instructor] Python provides a few different ways to delete files and directories. One way is with the OS module. We can use the remove method to delete an individual file given its file path. In this case, we're going to delete a screenshot, screenshot1. Another option for deleting files in Python is to use the pathlib module. We can create a path and then use the unlink method to delete the file. We'll create a path to screenshot2, and then use the unlink function. The OS module also provides an unlink method. It works pretty much the same as the remove method for a single file. Now, to delete a directory, we have a few options. If the directory is empty, we can use the OS or pathlib modules. For the OS module, we can use the remove dir method. We just deleted the screenshots and the screenshots folder, so we can delete the directory. For the pathlib module, we can create a path and then use remove dir. This…

Contents