Python Files हटाना
In this page:
import os
if os.path.exists("file_name"):
os.remove("file_name")
os.remove() से File हटाना
os.remove(path) दिए गए path पर मौजूद file को permanently delete कर देता है -- इसमें कोई built-in undo नहीं है, इसलिए इस तरह हटाई गई file वाकई गायब हो जाती है (सिवाय Python के बाहर मौजूद किसी operating-system-level recovery tool के)।
उदाहरण: Deleting a File with os.remove()
import os
with open("temp.txt", "w") as f:
f.write("data")
os.remove("temp.txt") # permanently deletes the file, no undo
print(os.path.exists("temp.txt"))
हटाने से पहले File का होना जाँचना
os.path.exists(path) True लौटाता है अगर उस path पर कोई file या folder मौजूद है, और os.remove() call करने से पहले इसे जाँचना पहले ही delete हो चुकी, कभी बनी ही न हो, या गलत नाम वाली file पर FileNotFoundError crash से बचाता है।
उदाहरण: Checking If a File Exists Before Deleting
import os
if os.path.exists("missing.txt"): # avoids a crash if the file isn't there
os.remove("missing.txt")
else:
print("File does not exist")
खाली Folder हटाना
os.rmdir(path) किसी folder को हटाता है, पर सिर्फ़ तभी जब वह पूरी तरह खाली हो -- अभी भी files या subfolders वाले folder पर इसे call करना OSError raise करता है, यह एक safety measure है जो एक ही साधारण call से content से भरे folder को गलती से हटने से रोकता है।
उदाहरण: Deleting an Empty Folder
import os
os.mkdir("empty_dir")
os.rmdir("empty_dir") # only works because the folder is empty
print(os.path.exists("empty_dir"))
Folder और उसके अंदर सब कुछ हटाना
shutil.rmtree(path) पूरे folder tree को एक साथ हटा देता है, जिसमें उसके अंदर की हर file और subfolder शामिल है, चाहे उसमें कितनी भी content क्यों न हो -- यह os.rmdir() से कहीं ज़्यादा शक्तिशाली (और कहीं ज़्यादा खतरनाक) है, क्योंकि यह सब कुछ हटाने से पहले कभी confirmation नहीं माँगता।
उदाहरण: Deleting a Folder and Everything Inside It
import os
import shutil
os.makedirs("full_dir/sub", exist_ok=True)
with open("full_dir/file.txt", "w") as f:
f.write("data")
shutil.rmtree("full_dir") # deletes the whole folder tree, files and all
print(os.path.exists("full_dir"))
Safer Deletion Patterns
वाकई महत्वपूर्ण data के लिए, एक "soft delete" pattern (किसी file को वाकई हटाने की बजाय एक designated trash/archive folder में rename या move करना) वह safety net देता है जो immediate, permanent deletion नहीं देती -- इससे file को वापस move करके गलती को undo किया जा सकता है।
उदाहरण: Safer Deletion Patterns
import os
import shutil
os.makedirs("archive", exist_ok=True)
with open("important.txt", "w") as f:
f.write("data")
shutil.move("important.txt", "archive/important.txt") # "soft delete" by moving instead of removing
print(os.path.exists("archive/important.txt"))
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: