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

JavaScript Functions

  Hi there, and welcome to another exciting lesson on JavaScript. If this is your first time here, please do well to check out our previous lessons. In the previous lesson, we were discussing JavaScript math methods. It was very intuitive as we got to learn how to use the various math methods. To proceed, we shall be looking at JavaScript functions.  A function in JavaScript like in every other programming language could be defined as a block of code that is written to perform a particular task, and this function is usually invoked or called before it is being implemented. We have been talking about methods throughout the previous lessons right. Do you know that those methods are actually functions? Yes they are functions. You can now have an overview of the importance of functions in every programming language. How do we create a function in JS? To create a function, you follow the format function functionName(Argument) {//Block of code }. Some functions do have a return val...

JavaScript Math Methods

Hello everyone, and welcome to another exciting JavaScript lesson. In the last lessons you have been seeing other methods being used in JS (for example, the string methods). We shall go further into exploring other methods. This time, it’s going to be math methods. Do not move an inch because it’s going to be a very exciting. Before we look at what a math method is, let’s have an overview of math objects. A math object in JavaScript is a static built-in object that includes properties and methods used in performing mathematical tasks. Talking about math properties, they have the syntax Math.property . Some examples are Math.E that returns Euler’s number, Math.PI that returns PI, Math.LN2 that returns the natural logarithm of 2, and many others. The various JavaScript methods contained in the math object, thus, make mathematical operations easier and reduce effort as well as time in math-oriented programming. Some JS methods include abs( ), ceil( ), cos( ), sqrt( ), pow( ), log( ) ...

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...