Python Files पढ़ना
In this page:
with open("file_name", "r") as file:
content = file.read()
पूरी File पढ़ना
f.read() पूरी file की content को एक बार में memory में एक ही string में load कर देता है -- छोटी files के लिए सुविधाजनक है, पर बहुत बड़ी files के लिए जोखिम भरा है क्योंकि आपके program के processing शुरू करने से पहले ही पूरी चीज़ RAM में समानी चाहिए।
उदाहरण: Reading Entire File
with open("data.txt", "w") as f:
f.write("all content at once")
with open("data.txt", "r") as f:
print(f.read()) # loads the whole file into one string in memory
Line by Line पढ़ना
किसी file object पर सीधे loop चलाना ('for line in f:') पूरी file को पहले memory में load किए बिना एक बार में एक line पढ़ता है, जो gigabytes के size वाले logs या datasets को process करने के लिए memory-efficient विकल्प बनाता है।
उदाहरण: Reading Line by Line
with open("data.txt", "w") as f:
f.write("line1\nline2\n")
with open("data.txt", "r") as f:
for line in f: # reads one line at a time, without loading the whole file first
print(line.strip())
सभी Lines को List में पढ़ना
f.readlines() पूरी file पढ़ता है और उसे strings की एक list के रूप में लौटाता है, हर line के लिए एक string -- line-by-line loop के विपरीत, यह सब कुछ memory में load कर देता है, पर बाद में किसी specific line number को index करने की सुविधा देता है।
उदाहरण: Reading All Lines into a List
with open("data.txt", "w") as f:
f.write("a\nb\nc\n")
with open("data.txt", "r") as f:
lines = f.readlines() # loads every line into a list of strings
print(lines)
Missing Files की Safe Reading
ऐसा path खोलने की कोशिश करना जो मौजूद ही नहीं है, FileNotFoundError raise करता है, इसलिए production code आमतौर पर file-opening को try/except block में लपेटता है ताकि raw traceback के साथ program crash होने देने की बजाय एक स्पष्ट error message दिखाया जा सके।
उदाहरण: Safe Reading of Missing Files
try:
with open("missing.txt", "r") as f:
print(f.read())
except FileNotFoundError: # raised because the path doesn't exist
print("File not found")
Newline Characters हटाना
किसी file से पढ़ी गई lines अपना trailing '\n' newline character साथ रखती हैं, इसी वजह से पढ़ने के तुरंत बाद अक्सर आगे की processing से पहले text साफ़ करने के लिए line.strip() या line.rstrip('\n') लगाया जाता है।
उदाहरण: Stripping Newline Characters
with open("data.txt", "w") as f:
f.write("hello\n")
with open("data.txt", "r") as f:
line = f.readline()
print(repr(line)) # shows the trailing \n that was read from the file
print(repr(line.strip())) # newline removed
Chapter Quiz — Complete all 6 topics to unlock
0/6 topics done
Complete these topics first: