python

How to delete a file or directory in Python

How to delete a file or a directory in Python? In this tutorial, we will see how to delete one or more files or directories, if they exist.
 

How to delete a file in Python?

To delete a file in Python, you have to import the OS module and execute the function os.remove(). You must first check whether the file exists or not, otherwise, the program will generate an error.
 

 

Methods to delete a file or directory in Python

These are the methods to delete files and directories.

  • os.remove() – Removes a file.
  • os.rmdir() – Deletes an empty directory.
  • shutil.rmtree() – Deletes a directory and its contents.

 

Syntax to delete a file

You need to import the OS module to delete a file in python.

import os
os.remove("/path/file.txt")

OR, if the file is in the current directory

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

Since os.remove() can throw an “OSError” exception if the path doesn’t exist, we need to check if the file exists, and then remove it.

import os

#we should check whether the file exists or not before deleting it.
if os.path.exists('/path/file.txt'):
    os.remove('/path/file.txt')
else:
    print("Cannot delete file because it does not exist")
 

Syntax to delete a directory

To delete a directory, you must use os.rmdir() method, which will delete only empty directory.

import os
os.rmdir("myDirectory")

 

Delete multiple files

To delete multiple files, we simply iterate through the list of file and use os.rmdir() function.

To delete a directory containing all the files, you must import the “shutil” module. Then you can delete the directory as follows.

import shutil
shutil.rmtree('myDirectory')
mcqMCQPractice competitive and technical Multiple Choice Questions and Answers (MCQs) with simple and logical explanations to prepare for tests and interviews.Read More

Leave a Reply

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