Python program to delete a file

Here, we will write a Python program to delete a file present in the same folder as the program.
Submitted by Shivang Yadav, on March 17, 2021

Python programming language allows its users to manipulate the files, you can rename a file or even delete it using python commands.

The methods that can be used to perform these tasks are imported in the python program using os library in python.

Deleting a file

Deleting a file will simply delete the given file from its directory. This is done using remove() method present in os library.



The method accepts the path or path of the file to be deleted.

We can delete a file present in your system using remove() method by entering the full path of the file to the function.

Here, we will see how to delta a file present in the same directory. For this, we need to directly pass the name of the directory in python.

Program to delete a file in python

# importing os library...
import os

# main method 
def main():
    # removing file using remove method 
    print("File 'data.txt' is deleted!")

if __name__=="__main__":main()


File 'data.txt' is deleted!


In the above code, we have deleted the file data.txt using the os.remove() method.

Python file handling programs »


Comments and Discussions!


Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing
» Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© some rights reserved.