Python File Handling परिचय
In this page:
File Streams का परिचय
File handling यह है कि कोई program disk पर persist रहने वाली files से data कैसे पढ़ता है या उनमें कैसे लिखता है, भले ही program खत्म हो जाए -- memory में मौजूद variables के विपरीत, किसी saved file की content आपकी script के अलग-अलग runs के बीच बनी रहती है।
उदाहरण: Introduction to File Streams
with open("notes.txt", "w") as f:
f.write("saved to disk") # writes and persists to disk
with open("notes.txt", "r") as f:
print(f.read()) # reads it back, even in a fresh run
open() Function
open() हर file काम का entry point है -- यह एक file path और एक mode string (r पढ़ने के लिए, w लिखने के लिए, और अन्य) लेता है और एक file object लौटाता है जिस पर आप फिर .read() या .write() जैसे methods call करते हैं।
उदाहरण: The open() Function
f = open("notes.txt", "w") # "w" mode opens the file for writing
f.write("hello")
f.close()
f = open("notes.txt", "r") # "r" mode opens the file for reading
print(f.read())
f.close()
Files बंद करना
आपकी खोली हर file को आख़िर में .close() से बंद करना चाहिए -- यह operating system का file handle release करता है और, write mode में खोली गई files के लिए, यह सुनिश्चित करता है कि buffered data वाकई disk पर flush हो जाए, बजाय इसके कि program अचानक exit होने पर वह खो जाए।
उदाहरण: Closing Files
f = open("notes.txt", "w")
f.write("data")
f.close() # releases the file handle and flushes buffered data
print(f.closed)
with Statement
'with open(...) as f:' pattern indented block खत्म होते ही आपके लिए अपने आप .close() call कर देता है, भले ही उसके अंदर कोई exception क्यों न raise हो -- इसी वजह से open() और close() calls को manually pair करने की बजाय files के साथ काम करने का यह recommended तरीका है।
उदाहरण: The with Statement
with open("notes.txt", "w") as f:
f.write("safe write")
print(f.closed) # automatically closed after the block
File Modes का Overview
बुनियादी r (पढ़ना) और w (लिखना, जो मौजूदा content मिटा देता है) के अलावा, a मौजूदा data को छुए बिना file के अंत में नया data जोड़ता है, और x बिल्कुल नई file बनाता है पर अगर उस path पर पहले से कोई file है तो FileExistsError raise करता है -- यह गलती से overwrite होने से बचाने वाली एक safety check के रूप में उपयोगी है।
उदाहरण: File Modes Overview
with open("log.txt", "w") as f:
f.write("first line\n") # "w" mode starts the file fresh
with open("log.txt", "a") as f:
f.write("appended line\n") # "a" mode adds to the end without erasing
with open("log.txt", "r") as f:
print(f.read())
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: