-
Hajipur, Bihar, 844101
In Python, you can delete files using the os
module.
First, import it:
import os
import os
os.remove("sample.txt")
✅ Deletes the file named sample.txt
.
import os
if os.path.exists("sample.txt"):
os.remove("sample.txt")
else:
print("File does not exist")
✅ Prevents error if the file is missing.
import os
os.rmdir("myfolder")
✅ Removes the folder only if it’s empty.
For non-empty folders, use shutil
:
import shutil
shutil.rmtree("myfolder")
⚠️ Use carefully — this deletes everything inside the folder.
try:
os.remove("data.txt")
except FileNotFoundError:
print("File not found")
✅ Helps avoid crashes when the file doesn’t exist.
import os
for file in os.listdir():
if file.endswith(".log"):
os.remove(file)
✅ Deletes all .log
files in the current directory.
Q1. Write a Python program to delete a file named demo.txt
using os.remove()
.
Q2. Write a Python program to delete a file only if it exists, using os.path.exists()
.
Q3. Write a Python program to delete a folder named temp
only if it’s empty, using os.rmdir()
.
Q4. Write a Python program to use try/except
to safely delete a file that might not exist.
Q5. Write a Python program to use a loop to delete all .bak
files from a directory.
Q6. Write a Python program to use shutil.rmtree()
to remove a folder with all its contents.
Q7. Write a Python program to define a function that deletes a file if it is found, and returns success or failure.
Q8. Write a Python program to remove a folder and handle permission errors using a try/except
block.
Q9. Write a Python program to prompt the user to enter a file name and delete it if it exists.
Q10. Write a Python program to log a message when a file is deleted successfully (e.g., print "File deleted."
).
Q1: Which module is used to delete files in Python?
Q2: What does os.remove("file.txt") do?
Q3: What happens if the file doesn’t exist in os.remove()?
Q4: What is used to delete folders in Python?
Q5: Which module can delete a folder with contents?
Q6: What does shutil.rmtree("folder") do?
Q7: What is the best way to check if file exists before deleting?
Q8: Which function is used to list all files?
Q9: What type of error is raised if file not found?
Q10: Can os.remove() delete directories?