Delete Files in Python
To delete a file in Python, use the os.remove()
function from the os
module.
Python में किसी file को delete करने के लिए os.remove()
function का उपयोग किया जाता है।
Step 1: Import os Module
import os
Example 1: Delete a File
import os
os.remove("test.txt")
This will delete test.txt
if it exists.
यह test.txt
file को delete कर देगा अगर वह मौजूद है।
Example 2: Check if File Exists Before Deleting
import os
filename = "log.txt"
if os.path.exists(filename):
os.remove(filename)
print("File deleted.")
else:
print("File not found.")
Always check if file exists to avoid errors.
Error से बचने के लिए file के मौजूद होने की जांच करें।
Example 3: Try Except for Safe Delete
import os
try:
os.remove("data.txt")
print("File removed.")
except FileNotFoundError:
print("File not found.")
Use try/except
to handle exceptions if file is missing.
try/except
का use करके error को handle करें।