How to delete Python file or folder?

How to delete Python file or folder?

You can easily delete the files and folders in Pythin by using os.remove():

You can use os.remove() to delete a file in Python. This function removes a specified file.

import os
os.remove('path/to/your/file.txt') // Replace with your file path

This will delete the specified file. If the file doesn’t exist, it will raise a FileNotFoundError.

Hope this was helpful :slight_smile:

hey @raimavaswani

I used this methis : os.rmdir() to delete an empty folder: To delete an empty folder, you can use os.rmdir(). It removes the folder, but only if it is empty.

import os
os.rmdir('path/to/your/folder')  # Replace with your folder path

This will delete the folder if it is empty. If the folder contains files or other folders, it will raise an OSError.

Using shutil.rmtree() to delete a folder with contents: If you need to delete a folder and all of its contents (files and subfolders), you can use shutil.rmtree().

import shutil
shutil.rmtree('path/to/your/folder')  # Replace with your folder path

This will recursively delete the folder and everything inside it, including all files and subfolders.