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.
How to Python Delete File?
To delete a file in python, you must import the OS module, and run its
os.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.
os.remove()– Remove (delete) the file path.
os.rmdir()will remove an empty directory.
shutil.rmtree()will delete a directory and all its contents.
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")
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 :
- 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
import os os.rmdir("folderName")
Delete multiple files
To delete multiple files, just loop over your list of files and use the above
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?
Do comment if you have any doubt and suggestion on this tutorial.
:This example (Project) is developed in PyCharm 2018.2 (Community Edition)
JVM: OpenJDK 64-Bit Server VM by JetBrains s.r.o
All Example Python delete
fileif exists are in Python 3, so it may change its different from python 2 or upgraded versions.
Degree in Computer Science and Engineer: App Developer and has multiple Programming languages experience. Enthusiasm for technology & like learning technical.