Python Delete File | Remove File | Multiple Files if exists

How you will delete a file in python? In this tutorial, you will learn about Python delete files (single or multiples) if the file exists. Must recommend reading the Python Create File because in this tutorial we are deleting the same files, which create in previous tutorials.

Python Delete File | Remove File | Multiple Files if exists

How to Python Delete File?

To delete a file in python, you must import the OS module, and run itsos.remove() function or other modules with functions. You must check before the file is available or not, else the program will throw an error.

Delete methods in Python

This is the python delete methods for file and folders.

Python syntax to delete a file

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

import os
os.remove("/path/<file_name>.txt")

OR

if the file in the same place of project

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

Python Delete File Example 

First, check whether the file or folder exists or not then only delete that file. This can be achieved in two ways :

  •   os.path.isfile(“/path/fileName”)
  •  or use exception handling.

We assume have a file in project “cFile.txt.” , for detail read the previous tutorial Create File tutorial. Check below the example program of how to python delete a file if exists.

import os
if os.path.exists("cFile.txt"):
  os.remove("cFile.txt")
else:
  print('File does not exists')

if the file does not exist then the output will be print()File does not exist”

Python Delete Folder/Directory

To delete an entire folder, you have to use the os.rmdir() method. It will delete the only empty folder. For complete delete for the file in a folder using shutil.rmtree().

import os
os.rmdir("folderName")

Delete multiple files

To delete multiple files, just loop over your list of files and use the above os.rmdir() function.

To delete a folder containing all files you want to remove have to import shutil package. Then you can remove the folder as follows.

import shutil
shutil.rmtree('my_folder')

Do comment if you have in doubt or suggestion or code. This chapter comes under the Python File Handling section.

Exercise | Practice

  • How do I delete a specified number of files in a directory in Python?
  • How to remove a file if exists and handle errors?

Python File Handling Quiz

Python File Handling to test your knowledge – ( Create, Open, Update, delete and more about in Python)
It’s for Beginners, Advanced and Experienced Programmers.

Do comment if you have any doubt and suggestion on this tutorial.

Note: This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JRE: 1.8.0
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
macOS 10.13.6
Python 3.7
All Example Python delete file if exists are in Python 3, so it may change its different from python 2 or upgraded versions.


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.