File HandlingLesson 51Free preview
Python Delete Files
This lesson is part of Python · All levels
Summary
To delete files, Python provides the OS and pathlib modules. The classic method is os.remove(path), while the modern method is Path.unlink(). Both throw errors when files are not present, so it is best to check them first with os.path.exists() or handle them through try/except. To delete the folder and contents is available a shutil module.
Key points
- Os.remove(path) deletes a file; Path(path).unlink() is a modern equivalent method.
- The missing file is generating a FileNotFoundError, so check first or handle with try/except.
- Shutil.rmtree(path) deletes the entire folder along with its contents.
- Make sure the path is correct before deleting, especially when using the absolute path.
Full lesson
Code examples and quizzes
Full lessons, code examples, and quizzes are available to subscribers. 5 questions.