All TalkersCode Topics

Follow TalkersCode On Social Media

devloprr.com - A Social Media Network for developers Join Now ➔

How To Delete A File In Python

Last Updated : Mar 11, 2024

How To Delete A File In Python

In this article we will show you the solution of how to delete a file in python, Python files are used for various purposes by developers. Developing a file requires understanding the procedure for deleting it once a developer is finished with it.

During the development of a large program, the developer would need to create files to store the data, but they wouldn't be required after the program was executed.

Our goal in this tutorial is to discuss methods in Python for removing a file using the os.remove() function and the pathlib module.

Files or file paths can be deleted with this module, but directories cannot be deleted.

In this case, an OSError will be raised if the specified path is a directory.

We will now discuss the idea of how to delete a file in python with an example.

Step By Step Guide On How To Delete A File In Python :-

import pathlib
path="Text_files"
if not os.path.exists(path):
    # creating a new folder
    os.makedirs(path)
# fetching the working directory path
rootdir=os.getcwd()
for dir files in os.walk(top=dir, topdown=False):
    for name in dirs:
        dir_path=os.path.join(root, name)
        print("Subdirectory",dir_path)
print("We can see a folder created successfully with name Text_files")
print("-----------------------------------------------------")
myfile = "tc.txt"
new=os.path.join(dir_path,myfile)
Path(new).touch()
print("Files in a directory -->",os.listdir())
# Try to delete the empty folder
# checking for folder availability using try and except block
try:
    os.rmdir(dir_path)
    for dir files in os.walk(top=dir, topdown=False):
        if dirs==[]:
            print("No subdirectory")
        else:
            print(dirs)
    print("folder deleted successfully")
    print("-----------------------------------------------------")
except OSError as e:
    print("error: %s - %s." % (e.filename, e.strerror))
    print("-----------------------------------------------------")
  1. In this code, a new folder is created, a new file is created in a subdirectory, and then an empty folder is deleted.
  2. It is first necessary to create a variable named 'path' that contains the name of the new folder that will be created.
  3. Our next step is to verify whether the folder already exists in the current working directory, by using the os.path.exists() function. Our code creates the folder if it does not exist using os.makedirs().
  4. In the next step, we retrieve the current working directory path using os.getcwd().
  5. Our next step is to iterate through all the subdirectories and files within the working directory using a for loop. Each subdirectory's full path is printed for each found subdirectory.
  6. The last subdirectory should contain a new empty file called "tc.txt", which is created using pathlib.Path().touch().
  7. As a final step, we will use the os.rmdir() method to get rid of the subdirectory created earlier. A successful deletion will occur if the subdirectory is empty. In the event that it is not empty, an OSError will occur, which will be handled by the try-except block.
  8. In order to verify whether the folder was successfully deleted, we check if it was successfully deleted. If there are no subdirectories in the working directory, we print "No subdirectory", otherwise, we print the list of directories.

Conclusion :-

As a result, we have successfully learned how to delete a file in python with an example.

Here are some fundamental concepts that will guide you after learning about Python's deletion of files.

There are primarily three techniques for removing files in Python. Python's os module enables us to leverage operating system-specific features.

Shutil allows you to delete folders and all of the files and subdirectories included within them.

The file or symbolic link is deleted using the unlink() method.

I hope this article on how to delete a file in python helps you and the steps and method mentioned above are easy to follow and implement.

Author Image About Ashish

Ashish is a dynamic and motivated individual with a passion of programming and an experienced programmer having 3+ years of experience in various languages like Java, Python, HTML, CSS, JavaScript, jQuery and various frameworks like Bootstrap

Follow Ashish On Linkedin 🡪