Python os मॉड्यूल
In this page:
import os
os.getcwd()
os.listdir(path)
os.path.join(part1, part2)
Working Directory प्राप्त करना
os मॉड्यूल आपकी script और underlying operating system के बीच मुख्य interface है।
os.getcwd() उस directory का absolute path लौटाता है जहाँ से आपका program शुरू हुआ था या जिसमें बाद में बदल गया, जो अक्सर बाकी relative paths बनाने के लिए reference point होता है।
उदाहरण: Getting Working Directory
import os
print(os.getcwd())
Folders बनाना और मिटाना
os.mkdir() एक नई directory बनाता है और अगर path में कोई parent directory पहले से मौजूद नहीं है तो fail हो जाता है, जबकि os.makedirs() ज़रूरत की पूरी chain की intermediate directories बना देता है।
os.rmdir() किसी directory को तभी हटाता है जब वो पूरी तरह खाली हो, और अगर उसमें अब भी files हों तो delete करने से मना कर देता है।
उदाहरण: Creating and Deleting Folders
import os
os.makedirs("demo_dir/sub", exist_ok=True) # creates every intermediate directory needed
os.rmdir("demo_dir/sub") # only works because the directory is empty
print("Folder created and removed")
Directory की सामग्री List करना
os.listdir(path) दी गई folder के अंदर मौजूद हर file और subdirectory का नाम एक साधारण strings की list के रूप में लौटाता है, बिना दोनों तरह की entries में फ़र्क़ किए।
आप आमतौर पर इसके बाद os.path.isfile() या os.path.isdir() का इस्तेमाल करते हैं अगर आपको files और folders में अंतर करना हो।
उदाहरण: Listing Directory Contents
import os
print(os.listdir("."))
Paths को Join और Split करना
साधारण string concatenation से file paths बनाना अलग-अलग operating systems पर टूट जाता है, क्योंकि Windows backslashes इस्तेमाल करता है जबकि Unix-जैसे systems forward slashes।
os.path.join() उस platform के लिए सही separator डाल देता है जिस पर code चल रहा है, इसलिए एक ही code हर जगह valid paths बनाता है।
उदाहरण: Joining and Splitting Paths
import os
path = os.path.join("folder", "file.txt") # inserts the correct separator for the current OS
print(path)
File का अस्तित्व Check करना
os.path.exists() यह जाँचता है कि दिए गए path पर कुछ भी -- file या directory -- मौजूद है या नहीं, और अगर नहीं है तो error की बजाय False लौटाता है।
os.path.isfile() और os.path.isdir() इस check को और सटीक बनाते हैं, जिससे आप यह भी पक्का कर सकते हैं कि path किस तरह की चीज़ है।
उदाहरण: Checking File Existence
import os
print(os.path.exists(".")) # True whether it's a file or a directory
print(os.path.isdir(".")) # confirms it's specifically a directory
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: