Lokasi ngalangkungan proxy:   [ UP ]  
[Ngawartoskeun bug]   [Panyetelan cookie]                
Skip to content
No results
  • About AskPython
  • Blog
  • Contact Me
  • Free Online Developer Tools Hub
  • Home
  • Meet the Team
  • Privacy Policy
  • Python
  • Python Course for Beginners Online FREE
  • Python Tutorial – Mega Index
  • Terms and Conditions

🚀 Supercharge your YouTube channel's growth with AI.

Try YTGrowAI Free
  • Home
  • Blog
  • About AskPython
  • Python Course
  • Start Here

How To Delete Files in Python

  • SnehSneh
  • February 1, 2020
  • Python Programming
How To Delete Files in Python

Introduction

In our Python file handling Tutorial, we learned how to manipulate files from within Python. In this tutorial, we’ll learn how to delete files in Python.

We know how to read from and write to a file in Python. Let’s learn the delete operation in Python today.

Suppose after successfully creating a file, we perform some operations on it like reading and writing. As soon as we are done using the file for analyzing different sets of data, maybe in some cases, we don’t need it in the future. At this point how do we delete the file? In this tutorial, we are going to learn that.

Methods to Delete Files in Python

Let us take a look at the different methods using which we can delete files in Python.

1. Using the os module

The os module in Python provides some easy to use methods using which we can delete or remove a file as well as an empty directory. Look at the below-given code carefully:

import os
if os.path.isfile('/Users/test/new_file.txt'):
    os.remove('/Users/test/new_file.txt')
    print("success")
else:    
    print("File doesn't exists!")

Here we have used an if-else statement to avoid the exception that may arise if the file directory doesn’t exist. The method isfile() checks the existence of the file with filename- ‘new_file.txt’.

Again, the os module provides us with another method, rmdir(), which can be used to delete or remove an empty directory. For example:

import os
os.rmdir('directory')

Note: The directory must be an empty one. If it contains any content, the method we return an OSerror.

2. Using the shutil module

The shutil is yet another method to delete files in Python that makes it easy for a user to delete a file or its complete directory(including all its contents).

rmtree() is a method under the shutil module which removes a directory and its contents in a recursive manner. Let us see how to use it:

import shutil
shutil.rmtree('/test/')

For the above-mentioned code, the directory ‘/test/’ is removed. And most importantly, all the contents inside the directory are also deleted.

3. Using the pathlib module

pathlib is a built-in python module available for Python 3.4+. We can remove a file or an empty directory using this pre-defined module.

Let’s go for an example:

import pathlib
file=pathlib.path("test/new_file.txt")
file.unlink()

In the above example, the path() method is used to retrieve the file path whereas, the unlink() method is used to unlink or remove the file for the specified path.

The unlink() method works for files. If a directory is specified, an OSError is raised. To remove a directory, we can resort to one of the previously discussed methods.

References

  • https://stackoverflow.com/questions/6996603/how-to-delete-a-file-or-folder
  • https://docs.python.org/3/library/os.html#os.remove
  • https://docs.python.org/3/library/shutil.html
  • https://docs.python.org/3/library/pathlib.html
Sneh
Sneh
Articles: 36
Python Set Difference
Previous Post Python Set Difference
Next Post Python String lower() Method
Python String lower() Method

Related Posts

What Does %s Mean in Python String Formatting?

What Does %s Mean in a Python Format String?

  • November 30, 2026
Python Convert String to List

Python Convert String to List: Choose the Right Method

  • November 29, 2026
Translate String Python

Translate String Python

  • November 29, 2026

Partner Websites

  • GoLangDocs
  • LinuxForDevices
  • CodeForGeek

Popular Categories

  • Python Programming
  • Python Modules
  • OOPS in Python
  • Python Programming Examples
  • Strings in Python

Hall of Fame

  • Python Programming
  • OOPS in Python
  • Creating Python Modules
  • Args and Kwargs in Python
  • Python Dictionary (Dict) Tutorial
  • Python List – 15 Things You MUST Know
  • Python Set – Things You MUST Know
  • Python String Functions: Methods by Task

Important Links

  • Home
  • Python Course
  • Start Here
  • Blog
  • About AskPython
Latest posts
  • np.linalg.eig: Eigenvalues and Eigenvectors
  • What Does %s Mean in a Python Format String?
  • How to Use np.sin() in NumPy
  • cv2.imread: Load Images with OpenCV
  • pd.read_json: Read JSON Into a DataFrame

Copyright © 2026 - AskPython. All rights reserved.