File handling (text and CSV files) using the CSV module; file modes: read, write, append

Python का open() आपको एक file तीन modes में से एक में थमाता है: r read करता है, w एक fresh file लिखता है (पुरानी को नष्ट करते हुए), a आख़िर में append करता है, और with statement इसे आपके लिए close कर देता है।

9 min read · 10 cards · 2 checks

Read in: English · हिन्दी · ગુજરાતી


Theory

सब कुछ database में नहीं रहता

ResultDesk marks के लिए college.db रखता है, पर दुनिया plain files भेजती रहती है: notes.txt में एक attendance log, .csv के रूप में mark sheets, कहीं लिखने के लिए error logs।

csv module commas parse कर सके (अगला lesson) उससे पहले, आपको ख़ुद file पकड़नी होगी: इसे खोलिए, lines निकालिए, lines लिखिए, data खोए बिना close कीजिए।

Python यह सब एक function से करता है, open(), और इसमें एक letter decide करता है क्या आप read करते हैं, write करते हैं, या गलती से destroy करते हैं।

Theory

एक notebook खोलने के तीन तरीक़े

वही notebook, तीन इरादे:

  • r: पढ़ने के लिए खोलिए, कुछ मत छुइए। Notebook missing है? आप हवा नहीं पढ़ सकते: error।
  • w: हर page फाड़ दीजिए और page एक से लिखना शुरू कीजिए। Missing? एक नई notebook ख़रीदी जाती है।
  • a: आख़िरी लिखे page पर खोलिए और नीचे जारी रखिए। Missing? नई notebook, वही behaviour।

फटे pages याद रखने की बात हैं: mode w एक pen लगा shredder है।

At a glance

File modes

Modeअगर file exist करती हैअगर file missing है
r (read)Reading के लिए खुलता हैFileNotFoundError
w (write)Empty तक TRUNCATE करता है, फिर लिखता हैनई बनाता है
a (append)मौजूदा content के बाद लिखता हैनई बनाता है
r+ (read+write)दोनों के लिए खुलता हैFileNotFoundError
b suffix (rb, wb)Binary mode (images, .db files)Base mode के अनुसार

Practical

Read, write, append: with pattern

# WRITE a fresh report (destroys any old report.txt!)
with open('report.txt', 'w') as f:
    f.write('DBMS average: 61.5\n')      # \n is YOUR job
    f.write('Maths average: 73.2\n')

# APPEND to a running log (never destroys)
with open('activity.log', 'a') as f:
    f.write('report generated\n')

# READ it back, line by line
with open('report.txt', 'r') as f:
    for line in f:                        # the file object is iterable
        print(line.strip())               # strip() removes the trailing \n

# other reading tools:
# f.read()       -> the whole file as one string
# f.readline()   -> one line
# f.readlines()  -> list of all lines

This example runs in Gri-Learn on the web, where you can edit it and see the output.

Theory

with क्यों, open/close क्यों नहीं

आप f = open(...) लिख सकते हैं और बाद में f.close()। Professionals लगभग कभी नहीं करते, क्योंकि जिस पल कोई error इसके ऊपर से कूद जाए close skip हो जाता है, files locked और writes unflushed छोड़ते हुए।

with open('report.txt', 'w') as f: file को automatically close करता है, यहाँ तक कि अगर block crash हो जाए। यह file-handling का transactions promise के बराबर है: cleanup जिसे भुलाया नहीं जा सकता।

एक और आदत: हर write() बिल्कुल वही output करता है जो आप देते हैं, कोई newline अपने आप नहीं जुड़ता। Line breaks आपका काम हैं: '\n'।

Quiz

attendance.log एक महीने के records रखता है। एक script आज की entry जोड़ने के लिए इसे open('attendance.log', 'w') से खोलती है, एक line लिखती है, close करती है। अब file में क्या है?

  1. सिर्फ़ आज की line: mode w ने open time पर महीने के records truncate कर दिया
  2. महीने के records plus आख़िर में आज की line
  3. महीने के records आज की line ऊपर के साथ
  4. कुछ नहीं: w mode को file के मौजूद न होने की ज़रूरत होती है
Show the answer

सिर्फ़ आज की line: mode w ने open time पर महीने के records truncate कर दिया

Mode w खुलते ही एक मौजूदा file को empty कर देता है, किसी write से PEHLE: script के open() के तुरंत बाद crash होने पर भी महीने की history चली गई। आख़िर में जोड़ना बिल्कुल वही है जिसके लिए a (append) मौजूद है। यह silent-truncation accident सबसे महंगा beginner file bug है: logs, reports और CSVs सब इससे मरते हैं।

Think first

Doubled gaps अंदाज़ा लगाइए

report.txt में दो lines हैं। एक student चलाता है:

with open('report.txt') as f:

for line in f:

print(line)

tap करने से पहले: output कैसा दिखता है, और क्यों?

Show the answer

हर line इसके बाद एक blank line के साथ print होती है। किसी file से पढ़ी हर line अपना trailing \n रखती है, और print() एक और जोड़ता है: प्रति line दो newlines, doubled spacing।

Fix: print(line.strip()) (या line.rstrip('\n'), या print(line, end=''))। छोटी detail, पर यह file loops के बारे में लगभग हर write-the-output exam सवाल में दिखती है। यह भी नोटिस कीजिए: कोई mode न देना 'r' मतलब है, default।

Watch out

तीन file-handling mark-losers

w जब आपका मतलब a था: history चुपचाप destroy हो गई। हर open-for-writing से पहले ख़ुद से पूछिए: fresh file, या continuation?

write() में missing \n: सब कुछ एक line पर उतर जाता है; write() कुछ नहीं जोड़ता।

missing file पर r: FileNotFoundError, w/a के उलट जो create करते हैं। ऊपर वाला exam table "file modes explain कीजिए" का जवाब है: इसे exists/missing columns के साथ reproduce कीजिए।

Theory

CSV files बस text files हैं

marks.csv को इस lesson के tools से खोलिए और आपको honest text मिलता है: प्रति line 101,DBMS,78। आप ख़ुद split(',') कर सकते हैं... जब तक एक name में comma न हो और आपका parser टूट न जाए। बिल्कुल इसीलिए csv module मौजूद है: वही open(), वही with, वही modes, plus एक parser जो format के edge cases जानता है। अगला lesson: reader, writer, और उनके Dict cousins।

Summary

Key takeaways

  • open(name, mode): r read करता है (missing पर error), w बनाता है/TRUNCATE करता है, a append करता है (missing पर बनाता है)।
  • Mode w open time पर एक मौजूदा file empty करता है: silent destroyer।
  • with open(...) as f: automatically close करता है, errors पर भी: professional default।
  • Files से पढ़ी lines अपना trailing \n रखती हैं: print से पहले strip() कीजिए; write() कोई newline नहीं जोड़ता।
  • read()/readline()/readlines()/iteration सभी reading styles cover करते हैं।
  • CSV files text files हैं; csv module इसके ऊपर comma-safe parsing जोड़ता है।
  • Memory hook: notebook पढ़िए, shred-and-write, या आख़िरी page पर जारी रखिए।

Study this properly

This page is the lesson to read. In Gri-Learn the same topic is a graded deck: the self-checks are scored and your weak topics are tracked. Free to start.

Start this topic

Already have an account? Sign in

More from Python interaction with text and CSV

Gri-Learn · syllabus-mapped B.C.A. lessons in English, Hindi and Gujarati