How to delete a file in Python?

PHPz
Release: 2023-09-13 09:01:01
forward
1038 people have browsed it

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)
Copy after login

Output

File data = Thisisit!
Copy after login

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
Copy after login

Import operating system module

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

import os
Copy after login

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")
Copy after login

Output

Deleting our file…
Copy after login

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!

Related labels:
source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!