Home  >  Article  >  Backend Development  >  How to delete a file in Python?

How to delete a file in Python?

PHPz
PHPzforward
2023-09-13 09:01:011113browse

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

Let's first create a file and read the contents: we will display the contents of a text file. To do this, we first create a text file with the following content amit.txt -

How to delete a file in Python?

Fileamit.txt is visible in the project directory -

How to delete a file in Python?

Display the contents of the text file

Now let us 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!

Deleting files in Python

To remove a file, pass the file name and path as arguments to the remove() method. Since the remove() method belongs to the OS module, the OS module is installed and imported first.

Install operating system modules

To install operating system modules, use the pip command -

pip install os

Import operating system module

This is how to import operating system modules in Python after installation -

import os

Now, let’s see an example of deleting the 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 above files. The file is now invisible in the project directory -

How to delete a file in Python?

The above is the detailed content of How to delete a file in Python?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete