Python

Python Delete File If Exists

This is the delete file in the Python section of our Python lesson. If you ever want to erase a file that you have written in this programming language, you will need to import the OS module first. After you have imported the OS module, use the os.remove() module or function to delete it. Python provides many methods for deleting files and directories. You can delete any file reliant on your needs. This article discusses some Python programs that delete a file entered by the user at runtime. We’ll utilize the os.remove(), os.rmdir(), and hutil.rmtree() methods to do this.

Example 1:

The OS module in Python includes functions for networking with the OS. All functions in the OS module throw OSError if the file names and paths are invalid or not accessible, or if other parameters have the correct type but aren’t accepted by the OS. To remove or erase a file path in Python, use the os.remove() method. A directory cannot be removed or deleted using this approach. If the supplied path is a directory, the procedure will throw an OSError. os.remove(path, *, dir_fd = None) is the syntax where a file path is represented by a path-like object called Path.

A path-like object is basically a string or a collection of bytes that describe a path. The file descriptor dir fd links to a directory. This parameter’s default value is None. dir_fd is ignored if the supplied path is absolute. The asterisk (*) in the parameter list denotes that the next arguments (in this case, ‘dir_fd’) are keyword-only parameters that can only be specified by name, not by position. One thing to note down is that the os.remove() function has no return value.

https://lh6.googleusercontent.com/_Dy-okDH8-XybNwzyCBWqqkqzePjz-NBkdaIZZO9LsZCRoGUzVDluDVN7ubr2cd-S2p_4TDBrR6HmcX5OiQAbCbnxKygmg6eD5Y15IukqE6cM1UnkRl4sVTTBIWeY9-6tbj-1OrH

The above snapshot shows the file that is contained within the folder. We are going to remove the demo_file1 from the folder. The implementation is shown below. This Python application demonstrates the os.remove() method.

First, we imported the OS module, and then we declared the file name in the file name folder. Following that, the path to the file that we wish to remove is defined. Now that we’ve joined the path and the file with the join function, we can use the os.remove method to delete a specific file.

import os

file_name = 'demo_file1.txt'

path = "D:/Projects/demo_files/"

file_path = os.path.join(path, file_name)

os.remove(file_path)

https://lh3.googleusercontent.com/2QkOx9f_tGiYpW5r8FzIGNY1bK7PegsdzVaeTUZhbrbybUjGpVWaouZbWrW_OJPxFF-chFFdMDAHDn6-Ul0r9DN8C2FfzNI7prto7Iu5sZms2l9H-81iFyZlaUCmsWwNSMETwQhH

Here, you can see that the specified file is deleted successfully.

https://lh6.googleusercontent.com/ZikFND__VKI_n8fRyth5THyB8vZ2whza--ufvSO8z0BtI7FWV8yNYpav0QguhOvxutkZe5Ledp4XTQAdAyWjK314QethusTZTq5r4FMb1dE3vE5FXhRPNKW-3kouFCay-2uiwHx8

Example 2:

Now, we will be discussing the os.rmdir() method. os.rmdir(path, *, dir_fd = None) is the syntax to follow. The os.rmdir() function is often used to delete a blank directory. An OSError will be upraised if the stated path is not a blank directory. os.rmdir(path, *, dir fd = None) is the syntax, where a path is a path-like object that specifies a file path.

A path-like object is just a string or a collection of bytes that describe a path. The file descriptor dir_fd is optional and refers to a directory. This parameter’s default value is None. This method doesn’t return anything either.

https://lh4.googleusercontent.com/Bv8qszgRcs5Je8jphuYds8ftsEG9ya9Tq2kreN7mtoWGvBQVGwvu-RA2klHhiCpeBl44nN4ZVSLDzJFv21PDz8opBOQQIEYe-a1JUVMmijHRFRRjPxQDMVhbe-E1lm4PEu7QQ4mO

In the above screenshot, you can view the directories. Suppose we want to remove the directory demo. The code for the removal of this directory is shown below. The os.rmdir() technique is explained in this program. We’ve already specified the directory we’d like to delete. The parent directory is then defined. Then, we’ve determined where the directory that we wish to delete is situated. Finally, os.rmdir is used to remove a directory by specifying a path.

import os

directory_name = "demo"

full_path = "D:/Projects/"

path_name = os.path.join(full_path, directory_name)

os.rmdir(path_name)

https://lh6.googleusercontent.com/x8_QwmUaad-5mlkKU0lN2smCEQO4TZWGSuSDV1zE_40OqJXY8-JTe369jyRjek8WAyrDYdaOtt_Nta1keS3kygV1Q210Q311amGoLr1Ii7LXVG29tAR8R3DoLLM6SRQRM8VGPywy

The directory demo is successfully removed as you can see below.

https://lh5.googleusercontent.com/XJyK079C4mJzJjf7pQEDokkIjrouShsMjSUi6r05dNOcDy7STJLe7HxCDEORxr44CXZg3Mpr79SVK9lDqDS79og1uer3Arh_GYAA4He5iEGTd_Tiih4IWkbR8U3eoeTyvKo4AvX8

Example 3:

The final example of this lesson is about the shutil.rmtree() method. Use the shutil.rmtree() function to delete a complete directory; path must link to a directory. shutil.rmtree(path, ignore_errors=False, onerror=None) is the complete syntax. It has three parameters: path, ignore_errors, and oneerror.

A file path is represented by a path-like object called Path. A path-like object is referred to as a string or a collection of bytes to show a path. If ignoring errors (another parameter) is true, errors caused by failed deletions will be entirely ignored. If ignore errors are false or omitted, such errors will be handled by calling the handler specified by onerror.

https://lh6.googleusercontent.com/2z0QFi7UPTS13R7hUaDxZaDSUbkeR4NaFbQGNjvd7KnJDNbNNw9pRgW3eav4WPtbQQoRZOP34XRoRd3ZHc4Uln5I2jzvqIRGhT1rf0RtsVHtgzcr3zhKQGPIPJbn9IC0GH57tUil

Assume the following directory structure and sub-directories. As you can see, our parent directory is a case study, and the directory inside the parent directory is case1 as you can see above.  The shutil.rmtree() method is demonstrated in this Python program. The initial code shows that the OS and shutil modules have been imported. After that, we define the file location as well as the directory we want to delete. The join function is used to join the directory’s location and name, and shutil.rmtree() is used to remove the directory.

import shutil

import os

loc = "D:/Projects/"

my_dir = "case study"

path = os.path.join(loc, my_dir)

shutil.rmtree(path)

https://lh3.googleusercontent.com/SnITTez-D4hA2AfDaJ4YVQtnSshkZA32RDzw21X11DOMFEKES7_qkrjF0Oe-cVsfeiAMXQTsxog4f2FOtF3R7faedb51Y6q8u99lxB6UhD1i5j8ymsP1q6rU3sHmfFnvpF75PmSU

The below output shows that the directory is now deleted.

https://lh5.googleusercontent.com/kfTD5WlXqr_8wxNwWFZdy5-82HK-3JLhjrjfadTHvsT1axfwBuGHsFZykBQP7tLNXAFCbT3dwXs15oxR8twB8pPiNOZ1NudcyBkT-jH_LaX_gO6y-dbxapojKw_KUfjAuOdMw_8m

Conclusion

We covered how to delete files in Python if they already exist. We deliberated over three different examples to clear the concept of deleting files in Python. Practical examples were given along with detailed explanations to assist you to grasp the idea.

About the author

Kalsoom Bibi

Hello, I am a freelance writer and usually write for Linux and other technology related content

Page was generated in 0.058015108108521