- Python Basic Tutorial
- Python - Home
- Python - Overview
- Python - Environment Setup
- Python - Basic Syntax
- Python - Comments
- Python - Variables
- Python - Data Types
- Python - Operators
- Python - Decision Making
- Python - Loops
- Python - Numbers
- Python - Strings
- Python - Lists
- Python - Tuples
- Python - Dictionary
- Python - Date & Time
- Python - Functions
- Python - Modules
- Python - Files I/O
- Python - Exceptions
- Python Advanced Tutorial
- Python - Classes/Objects
- Python - Reg Expressions
- Python - CGI Programming
- Python - Database Access
- Python - Networking
- Python - Sending Email
- Python - Multithreading
- Python - XML Processing
- Python - GUI Programming
- Python - Further Extensions
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)
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 −
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")
Deleting our file…
We have deleted the file above. The file won’t be visible in the Project Directory now −
- Related Articles
- How do I copy a file in python?
- How do I copy a binary file in Python?
- How do I create a .pyc file in Python?
- How do I read a .data file in Python?
- How do I wrap a string in a file in Python?
- How to delete a file using Python?
- How do I check whether a file exists using Python?
- How do I include a php.ini file in another php.ini file?
- How do I delete blank rows in MySQL?
- How do I send a DELETE keystroke to a text field using Selenium with Python?
- How do I delete array value from a document in MongoDB?
- How to Delete Specific Line from a Text File in Python?
- How can I source a Python file from another Python file?
- How do I loop through a JSON file with multiple keys/sub-keys in Python?
- Delete a file in C#