Skip to main content

How to delete files in python

How to delete files in python
Hi everyone. Welcome back to another session on python. If you are new here, please do checkout our previous articles on python and other programming languages. Also subscribe to our YouTube channel for the video tutorials.

In this tutorial, we are going to learn how to do the following in python

  • Deleting files in python
  • Checking if files still exist
  • Deleting folders in python

Deleting files in python

To delete a file in python, we can use the remove() which is called from the os module. This remove() method takes only one arguments.

syntax

os.remove(file_name)

Let’s demonstrate with an example

import os
# Delete file2.txt
os.remove(“file2.txt”)

After you must have deleted a file and you want to confirm if the file has been deleted or you might to check if the file still exist before deleting. Here is an example to check if a file has been deleted or still exist

import os
if os.path.exists("file2.txt"):
os.remove("file2.txt")
else:
print("The file does not exist")

Deleting folders in python

The method used in deleting folders in python is not that different from the method used when deleting files. When deleting folders we use the os.rmdir() method. Let’s illustrate with an example by deleting a folder called movies

import os
os.rmdir("movies")

Deleting python files with directories

We can remove a directory containing python with a method shutil.rmtree() which is located in the shutil library. With this method, we can clear off an entire directory file. Below is the syntax for the shutil method:

syntax

import shutil
shutil.rmtree(file_path)

Just like the os.remove(), we have imported shutil.rmtree() since an it’s part of an external library.

Let’s illustrate with an example on how to use this method. Let’s remove the final directory which is part of our grade analysis program. To remove the directory we use the following codes

import shutil
path = "/home/school/math/final"
shutil.rmtree(path)
print("/home/school/math/final has been removed.")

Python Os Error Handling

In some cases when we want to delete a file, the arguments can returned a permission error. There are times when we encounter error problems when using the three methods mention abovet. There is a way to handle these errors in case they arises, we can do this using the try except block. In the example below the compiler executes the lines of code within the try block and if an error is encountered, it will then run the within except block (if the OS Error is raised).

import os
path = "/home/school/math/final"
try:
os.rmdir(path)
print("/home/school/math/final has been deleted.")
except OSError as error:
print("There was an error.")

CONCLUSION

One of the common things we do in python is to remove files. We use the os.remove() to delete specific files, the os.rmdir() method can be used to remove an empty directory and the shutil.rmtree() method to delete a folder that contains one or more files.

Thank for reading guys. Happy coding 


Comments

Popular posts from this blog

Introduction to flask

Hello. Welcome to another session on this platform. If you are new here, please do checkout our previous articles on python programming language and stay excited on this session because we are entering into one of python’s web-based application called flask. In this article, we are going to see the following What is flask Prequistes Installation of flask in python Some of flask template engine. What is flask? Flask is one of python-based framework which is used to create web applications. Flight is a very light web framework. During installation, flask comes with pre-installed modules and functions which are used to backup your own web applications. Flask is very easy to understand and perfect go-to for beginners and with flask, a web server can run in less than 3 lines of code. Prequistes Before learning flask, we recommend the reader to have a basic mastery of python concepts. Installation of flask  Before installing flask, we have to checked if python has been installed or. If n...

How to generate random numbers using NumP1

Hello. Welcome to another edition on this platform. For more better understanding, do checkout our YouTube channel to get the video tutorial. In this article of today, we are going to see how to generate random numbers using any of the following methods: Generating a random number Generating a random float and integer Generating random number arrays Generating random number from an array What is a random number? This is a number which cannot be predicted before its occurrence. This number might not different every time. Programmatically, they are two categories of random numbers:     Pseudo-Random numbers       True Random numbers. Just as programs which are written by programmers are a set of instructions, we must follow an algorithm to generate random numbers. Random numbers which are generated using an algorithm are called Pseudo-Random numbers. To generate a true random number, it is important to get the data from sources such as the keyboards, mou...

Introduction to Django

Hello. Welcome to another session on this platform. If you are new here, please do checkout our previous articles on python programming language and stay excited on this session. we are entering into one of python’s application called Django. In this article, we are going to discuss the following: What is Django Why must we use Django  A brief history of Django Installation of Django Popularity of Django What is Django? Python has so many framework application and Django happen to be one of them. Being a python-based-framework, it is used to quickly create web applications.  When building websites, django provides similar ready-made components to handle user authentication, forms, a way to upload components. Why use django? Django is very fast. It takes applications from concept to applications very quickly Django has thousand available packages in it when it is installed. With django, we can launch web applications is a matter of hours. Django is a highly is secured and helps...