Python program to delete a file

Python | Delete a file: In this tutorial, we will learn how to delete a file in Python, and write a Python program to delete the given file. By Shivang Yadav Last updated : July 05, 2023

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.

How to delete a file in Python?

Deleting a file will simply delete the given file from its directory. You can use the remove() method of the os library to delete a file.

os.remove() method

The os.remove() method is a library method of the os library and it is used for removing or deleting a file, it cannot be used for removing the directory. To use this method you need to import the os module.

Syntax:

os.remove(file_path)

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.

Python program to delete a file

# importing os library...
import os

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

if __name__=="__main__":main()

Output

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!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.