To delete a file in Python, you can use the os.remove() function from the os module.
Deleting a File
import os
file_path = "filename.txt"
if os.path.exists(file_path):
os.remove(file_path)
print(f"{file_path} has been deleted.")
else:
print("The file does not exist.")
os.remove(file_path): Deletes the file at the specified path.
os.path.exists(file_path): Checks if the file exists before attempting to delete it, which helps avoid errors.
Using pathlib (Python 3.4+)
Alternatively, you can use the path class from pathlib for a more object-oriented approach.
from pathlib import Path
file_path = Path("filename.txt")
if file_path.exists():
file_path.unlink() # Deletes the file
print(f"{file_path} has been deleted.")
else:
print("The file does not exist.")
Python Delete File – Interview Questions
Q 1: How do you delete a file in Python?
Ans: Using os.remove('filename') from the os module.
Q 2: Can you delete multiple files at once?
Ans: Yes, by looping through filenames and using os.remove().
Q 3: What happens if the file does not exist?
Ans: An error is raised unless handled with try-except.
Q 4: Which module is used for file deletion?
Ans: The os module.
Q 5: How do you check if a file exists before deleting?
Ans: Using os.path.exists('filename')..
Python Delete File – Objective Questions (MCQs)
Q1. Which module is used to delete a file?
Q2. Which function deletes a file in Python?
Q3. What happens if os.remove("file.txt") is called for a non-existent file?
Q4. Which method deletes a directory instead of a file?
Q5. Which statement correctly checks if a file exists before deleting?