Languages
[Edit]
EN

Python - delete file

0 points
Created by:
Amir-Hashempur
547

In this article, we would like to show you how to delete a file using Python.

Quick solution:

import os
os.remove("example.txt")

 

Practical examples

1. Delete file

In this example, we import the os module and use os.remove() method to delete the example.txt file from our project.

import os
os.remove("example.txt")

or if the file is in a different location than our project we need to specify the path:

import os
os.remove("C:\\example_directory\\example.txt")

2. Safe way to delete the file

To avoid getting an error, check if the file exists first.

import os

if os.path.exists("example.txt"):
    os.remove("example.txt")
else:
    print("The file does not exist")
Donate to Dirask
Our content is created by volunteers - like Wikipedia. If you think, the things we do are good, donate us. Thanks!
Join to our subscribers to be up to date with content, news and offers.

Python - file operations

Native Advertising
🚀
Get your tech brand or product in front of software developers.
For more information Contact us
Dirask - we help you to
solve coding problems.
Ask question.

❤️💻 🙂

Join