Python pathlib मॉड्यूल
In this page:
from pathlib import Path
path = Path("folder/file_name")
path.exists()
path.read_text()
pathlib क्या है?
pathlib filesystem paths को plain strings की बजाय objects के रूप में represent करता है, और आपको manual string concatenation की बजाय methods और operators (जैसे joining के लिए /) देता है।
यह object-oriented approach उन cross-platform bugs को कम करती है जो hardcoded slashes से हाथ से paths बनाने पर आते हैं।
उदाहरण: What is pathlib?
from pathlib import Path
p = Path("folder") / "file.txt" # / joins path segments
print(p)
Path Properties निकालना
एक Path object सामान्य path हिस्सों के लिए पहले से बने properties देता है: containing directory के लिए .parent, आखिरी filename component के लिए .name, और file extension के लिए .suffix।
इन्हें किसी raw string से खुद निकालने में नहीं तो fragile string-splitting logic लिखनी पड़ती।
उदाहरण: Extracting Path Properties
from pathlib import Path
p = Path("/home/user/notes.txt")
print(p.parent) # containing directory
print(p.name) # final filename component
print(p.suffix) # file extension
File का अस्तित्व Check करना
Path.exists() किसी file को खोलने या पढ़ने की कोशिश करने से पहले यह चेक करता है कि path असल में disk पर किसी चीज़ की ओर इशारा करता है या नहीं, जिससे आप अपने program के logic में गहराई पर unhandled FileNotFoundError आने की बजाय एक साफ़ message के साथ gracefully fail कर सकते हैं।
उदाहरण: Checking File Existence
from pathlib import Path
p = Path(".")
print(p.exists()) # checks the path is actually on disk before using it
Files पढ़ना और लिखना
Path.read_text() और Path.write_text() (और इनके _bytes versions) किसी file की पूरी सामग्री को एक ही call में पढ़ या लिख देते हैं, बिना file handle खोलने, पढ़ने, और बाद में उसे बंद करना याद रखने के boilerplate के।
उदाहरण: Reading and Writing Files
from pathlib import Path
p = Path("notes.txt")
p.write_text("hello") # writes without manually opening/closing a file
print(p.read_text()) # reads the whole file in one call
Directories के साथ काम करना
Path.mkdir() नई directories बनाता है (ज़रूरत पड़ने पर intermediate directories बनाने के लिए parents=True option के साथ), और Path.iterdir() आपको किसी directory के अंदर मौजूद हर चीज़ पर loop चलाने देता है, और plain filename strings की बजाय Path objects वापस देता है।
उदाहरण: Working with Directories
from pathlib import Path
p = Path("demo_dir")
p.mkdir(exist_ok=True) # creates the directory, no error if it already exists
print(list(Path(".").iterdir())[:1]) # lists entries as Path objects
Chapter Quiz — Complete all 9 topics to unlock
0/9 topics done
Complete these topics first: