How do I delete a file in Python?


To delete a file, use the remove() method in Python. Pass the name of the file to be deleted as an argument.

Let us first create a file and read the content: We will display the contents of a text file. For that, let us first create a text file amit.txt with the following content −


The file amit.txt is visible in the Project Directory −


Display the contents of a text file

Let us now read the contents of the above file

# The file to be read with open("amit.txt", "r") as myfile: my_data = myfile.read() # Displaying the file data print("File data = ",my_data)

Output

File data = Thisisit!

Delete a File in Python

To delete a file, pass the file name and path as a parameter of the remove() method. The remove() method belongs to the OS module, therefore at first install and import the OS module.

Install OS Module

To install the OS Module, use the pip command −

pip install os

Import OS Module

This is how to import the OS module in Python after installing −

import os

Now, let us see an example to delete our file amit.txt −

import os # Delete the file amit.txt print("Deleting our file...") os.remove("amit.txt")

Output

Deleting our file…

We have deleted the file above. The file won’t be visible in the Project Directory now −


Updated on: 16-Sep-2022

1K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements