Python Delete File (2024)

Contents

Python – Delete File

To remove or delete a file using Python, call remove() method of os library with the path to the file passed as argument to the remove function.

In this tutorial, we shall learn how to delete a file, and different scenarios that we may encounter while deleting a file, like file not present, etc.

Syntax of os.remove()

Following is the syntax of remove() function.

os.remove('filepath')

If the file is present, remove() function deletes the file. But, if the file is not present, remove() function throws FileNotFoundError.

So, if you do not know if the file is present or not, and would not like to end up with FileNotFoundError at occasions, you may first check if the file is present and continue with the file removal process.

Examples

1. Remove given File

Following is an example to remove a file named data.txt present at the location same as that of the program.

Python Program

import osos.remove('data.txt')print('The file is removed.')

If your file is located somewhere else, other than your current directory, provide the full path (absolute path).

Python Program

import osos.remove('C:\workspace\python\data.txt')print('The file is removed.')
Python Delete File (1)

The file is successfully removed.

2. Try to remove a File that is not present

If the file specified by the provided path is not present, you will get FileNotFoundError error.

Python Program

import osos.remove('C:\workspace\python\aslkdjfa.txt')print('The file is removed.')

Output

FileNotFoundError: [WinError 2] The system cannot find the file specified: 'aslkdjfa.txt'

Summary

In this tutorial of Python Examples, we learned how to delete or remove a file using os Python library.

Next Topic ⫸ Python - Rename file

⫷ Previous Topic Python - Append to file

Python Delete File (2024)
Top Articles
Latest Posts
Article information

Author: Sen. Emmett Berge

Last Updated:

Views: 6811

Rating: 5 / 5 (60 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Sen. Emmett Berge

Birthday: 1993-06-17

Address: 787 Elvis Divide, Port Brice, OH 24507-6802

Phone: +9779049645255

Job: Senior Healthcare Specialist

Hobby: Cycling, Model building, Kitesurfing, Origami, Lapidary, Dance, Basketball

Introduction: My name is Sen. Emmett Berge, I am a funny, vast, charming, courageous, enthusiastic, jolly, famous person who loves writing and wants to share my knowledge and understanding with you.