To delete a file or folder using python, we must import os. Os library provides remove() function which we can use to delete any file. We can use rmdir() function to delete any directory.
Deleting a file
To delete a file having name hackersfriend.txt from current directory, we can write following code:
import os os.remove("hackersfriend.txt") #This will delelte hackersfriend.txt file from current directory
However, you should check if a file exists before attempting to delete it.
import os if os.path.exists("hackersfriend.txt"): os.remove("hackersfriend.txt") else: print("hackersfriend.txt does not exist in current directory")
Deleting a directory
To delete a directory we can use rmdir() function like this:
import os os.rmdir("hackersfriend")