Deleting Files in Python
gocourse.in Maintenance

We'll be back soon

Our CDN (cdn.gocourse.in) is currently unreachable. Some images, JavaScript, or CSS files may not load properly.

Estimated downtime: ~30 minutes

Deleting Files in Python

Kishore V


Deleting Files in Python

Python provides built-in support for removing files and directories using the os module. This allows your program to manage files safely and efficiently.

Removing a File

To delete a file, first import the os module and then use the os.remove() function.

Example: Delete a File

old_data.txt has been successfully deleted.

Checking File Existence Before Deletion

To avoid errors, it is a good practice to confirm that the file exists before deleting it.

Example: Safe File Deletion

File not found. It may have already been deleted.

Benefits of this approach:

  • Prevents runtime errors (like FileNotFoundError)
  • Safer for real-world applications

Deleting a Folder

To remove an empty directory, use the os.rmdir() method.

Example: Remove an Empty Folder

Folder 'temp_folder' created. Folder 'temp_folder' removed.

Our website uses cookies to enhance your experience. Learn More
Accept !