import os # Define the path of the file or folder to delete file_path = "path/to/file.txt" # Delete the file os.remove(file_path) # Define the path of the folder to delete folder_path = "path/to/folder" # Delete the folder (assuming it is empty) os.rmdir(folder_path)
To delete a file or folder in Python, you can use the os module and the os.remove() or os.rmdir() functions. In our example, we first import the os module. Then, we define the path of the file or folder we want to delete. To delete a file, we use the os.remove() function, which takes the file path as an argument. To delete a folder, we use the os.rmdir() function, which also takes the folder path as an argument.
Keep in mind that the os.remove() function can only be used to delete files, and the os.rmdir() function can only be used to delete empty folders. If you want to delete a folder that contains other files or folders, you will need to use a different approach.
Overall, the os module provides functions for deleting files and folders in Python. The os.remove() function can be used to delete files, and the os.rmdir() function can be used to delete empty folders. These functions are useful for cleaning up and managing files and folders in your Python scripts.
Python Mega Course: Learn Python in 60 Days, Build 20 Apps
Learn Python on Udemy completely in 60 days or less by building 20 real-world applications from web development to data science.