Python में फ़ाइल पढ़ना और लिखना
Programs अक्सर data files में save करते हैं और उसे वापस पढ़ते हैं। open() एक file object लौटाता है, और mode तय करता है कि आप read, write या append करेंगे।
में फ़ाइल पढ़ना और लिखना क्या है?
Programs अक्सर data files में save करते हैं और उसे वापस पढ़ते हैं। open() एक file object लौटाता है, और mode तय करता है कि आप read, write या append करेंगे।
open() और with से Python में text files लिखें, जोड़ें और पढ़ें।
इसका उपयोग कब करें?
- चलने योग्य code से Python syntax सीखें।
- बड़ी programming समस्याओं से पहले मजबूत आधार बनाएँ।
- स्थानीय setup के बिना किसी विचार को तुरंत जाँचें।
उदाहरण कोड
# "w" creates the file (or empties it) and opens it for writing.
with open("notes.txt", "w") as file:
file.write("first line\n")
file.write("second line\n")
# "a" appends to the end of an existing file.
with open("notes.txt", "a") as file:
file.write("third line\n")
# "r" (the default) reads. read() returns the whole file as one string.
with open("notes.txt") as file:
print(file.read())
# Loop over a file to read it line by line.
with open("notes.txt") as file:
for number, line in enumerate(file, start=1):
print(number, line.strip())
# "with" closes the file automatically, even if an error happens.
अपेक्षित आउटपुट
first line
second line
third line
1 first line
2 second line
3 third line
यह कैसे काम करता है
"w" file की contents को replace करता है, "a" end में जोड़ता है और "r" पढ़ता है। with block file को अपने-आप close कर देता है, even जब error हो।
मान बदलें और Python इंस्टॉल किए बिना CodeUtility ऑनलाइन Python कंपाइलर में प्रोग्राम चलाएँ।
अभ्यास के कार्य
बड़े dataset पर जाने से पहले input बदलें और edge cases की जाँच करें।
- Code चलाने से पहले output का अनुमान लगाएँ।
- खाली और गलत input संभालें।
- Logic को function में रखें और tests जोड़ें।
चैलेंज से अभ्यास करें
इस पाठ में सीखी बात से एक असली समस्या हल करें। हर चैलेंज ब्राउज़र में चलता है, तुरंत टेस्ट और AI रिव्यू के साथ।
सभी चैलेंज