Python File Delete

python-file-delete-ipcisco

In the previous lessons of this Python Course, we have learned how to create, read and write files in python with the help of Python open function. In this lesson, we will focus on Python File Delete. We will learn both how to delete files and directories in python.

 

In the previous file handling lessons, we have not import any additional modules to python. But to delete a file in python, we need an additional module. This module is “os” module. We need to import module os to delete a file in python programming.

 

With module os, we will use remove function of this module to delete files.

 


 

Removing Files in Python

 

Let’s firstly start how to delete files in python. To do this, we will import os module and use remove function in this module. We will show this with an example below.

 

Think about that we have a file named myfile.txt in the same directory with python. Now, we will delete this file with the following Python File Delete code.

 

import os
os.remove(“myfile.txt”)

 

python-file-delete-how-to-dekete-files-python

After this code, there will be no file like myfile.txt in the folder. To test it, we can use read mode. Because read mode will give an error, if there is no such a file.

 

x = open("myfile.txt", "r")
print(x.read())

 

The output of this code will be an error. Because, we have deleted myfile.txt and there is no such a file.

 


 

Removing Folders in Python

 

After learning how to delete files in python, now, let’s learn how to remove directories. To do this, we will use a different method named rmdir(). With rmdir() method, we will delete the complete folder in python. By the way, only empty folders can be removed with this method.

 

To remove a folder, again we should import module os. After that we will use rmdir() method in this module.

 

In the below example, we will delete folderx. Folderx is an empty folder.

 

import os
os.rmdir("folderx")

 

In this lesson, we have learned how to delete files and folders in python. We have focused Python File Delete methods with different examples.

 

Back to: Python Programming Course > Python File Handling

Leave a Reply

Your email address will not be published. Required fields are marked *

Python Programming Course

Collapse
Expand