Reading Files: read(), readline(), readlines() Differences Notes in Hindi & English : फाइल पढ़ना: read(), readline() और readlines() में अंतर और 20 महत्वपूर्ण MCQ प्रश्न (Rajasthan IT Exam)

Post a Comment

PGDCA, BCA, B-Tech, MCA, M-Tech, B.Sc computer science राजस्थान सूचना सहायक व कंप्यूटर शिक्षक विशेष नोट्स: इस अध्याय में हम Reading Files: read(), readline(), readlines() Differences (फाइल पढ़ना: read(), readline() और readlines() में अंतर) की संपूर्ण थ्योरी, मुख्य तकनीकी बिंदु, तुलनात्मक तालिका और विगत परीक्षाओं के पैटर्न पर आधारित 20 अति-महत्वपूर्ण बहुविकल्पीय प्रश्न (MCQs) विस्तृत हिंदी व अंग्रेजी व्याख्या सहित पढ़ेंगे।

Overview: Python offers read(), readline(), readlines(), and direct file iteration to consume file streams with distinct return types and memory footprints. Selecting the right method prevents MemoryError on large files and ensures accurate handling of trailing newlines and EOF markers.

अध्याय सार: पायथन में फाइलों को पढ़ने के लिए read(), readline(), readlines() और डायरेक्ट फाइल इटरेशन जैसे तरीके उपलब्ध हैं, जिनके रिटर्न टाइप और मेमोरी उपयोग भिन्न होते हैं। सही मेथड चुनने से बड़ी फाइलों में MemoryError से बचा जा सकता है और न्यूलाइन व EOF की सटीक पहचान होती है।

Reading Files: read(), readline(), readlines() Differences: Detailed Notes & Architecture (फाइल पढ़ना: read(), readline() और readlines() में अंतर)

1. read(size=-1): Whole-File or Fixed-Size Chunk Reading (read(size=-1): पूरी फाइल या निश्चित आकार के हिस्से पढ़ना)

[EN] `f.read()` with no argument (or `-1`) reads from the current cursor to EOF and returns one single `str` (in text mode) or `bytes` (in binary mode). Passing a positive integer `f.read(n)` reads at most `n` characters in text mode (not bytes—a 3-byte UTF-8 emoji counts as 1 character) or `n` bytes in binary mode. At End of File (EOF), `f.read()` returns an empty string `''` (or `b''` in binary mode) rather than raising an error. Because `f.read()` buffers everything in RAM at once, avoid calling it without a size limit on multi-gigabyte logs or datasets.

[HI] बिना आर्ग्यूमेंट (या `-1` के साथ) `f.read()` फाइल के वर्तमान पॉइंटर से अंत तक सारा डेटा एक ही `str` (या बाइनरी में `bytes`) के रूप में लौटाता है। `f.read(n)` टेक्स्ट मोड में अधिकतम `n` कैरेक्टर (अक्षर) और बाइनरी मोड में `n` बाइट्स पढ़ता है। फाइल के अंत (EOF) पर पहुंचने पर यह कोई एक्सेप्शन नहीं देता बल्कि खाली स्ट्रिंग `''` (या `b''`) लौटाता है। चूंकि `f.read()` पूरा डेटा एक साथ RAM में लोड करता है, इसलिए गीगाबाइट आकार की फाइलों पर बिना `size` दिए इसका प्रयोग नहीं करना चाहिए।

2. readline(size=-1): Streaming One Line at a Time (readline(size=-1): एक बार में एक पंक्ति पढ़ना)

[EN] `f.readline()` reads characters up to and including the next newline `'\n'` (or until EOF) and returns a single `str`. Crucially, `readline()` distinguishes a blank line from EOF: an empty line inside the file returns `'\n'` (truthy), whereas reaching EOF returns `''` (falsy). Passing `size > 0` caps the maximum characters read during that single call—so if a line has 100 chars and you call `readline(10)`, only the first 10 chars return and the remaining 90 stay for the next read. Calling `readline()` in a `while line := f.readline():` loop keeps RAM usage constant regardless of file size.

[HI] `f.readline()` अगली न्यूलाइन `'\n'` तक (न्यूलाइन सहित) या EOF तक पढ़कर केवल एक पंक्ति की स्ट्रिंग लौटाता है। यह फाइल के बीच की खाली पंक्ति और EOF में स्पष्ट अंतर करता है: खाली पंक्ति पर `'\n'` (सत्य/truthy) मिलता है, जबकि EOF पर `''` (असत्य/falsy) मिलता है। `readline(n)` देने पर यह एक बार में अधिकतम `n` अक्षर ही पढ़ता है और शेष अक्षर अगली कॉल के लिए छोड़ देता है। `while line := f.readline():` लूप बड़ी फाइलों के लिए बहुत कम मेमोरी का उपयोग करता है।

3. readlines(hint=-1): Materializing All Lines as a List (readlines(hint=-1): सभी पंक्तियों को लिस्ट में लोड करना)

[EN] `f.readlines()` reads all remaining lines until EOF and returns a Python `list` of strings (`list[str]`). Each string in the returned list retains its trailing `'\n'` character (except possibly the final line if the file lacks a trailing newline). An empty file yields an empty list `[]`. The optional `hint` integer sets an approximate byte threshold: once total bytes read exceed `hint`, `readlines(hint)` stops reading further lines—useful for chunked batch processing, though standard `readlines()` loads the whole file into memory.

[HI] `f.readlines()` फाइल की सभी शेष पंक्तियों को पढ़कर स्ट्रिंग्स की एक `list` लौटाता है। लिस्ट की प्रत्येक स्ट्रिंग में उसके अंत का `'\n'` कैरेक्टर शामिल रहता है (केवल अंतिम पंक्ति में यदि फाइल के अंत में न्यूलाइन न हो तो वह नहीं होगा)। पूरी तरह खाली फाइल होने पर `readlines()` खाली लिस्ट `[]` लौटाता है। वैकल्पिक पैरामीटर `hint` बाइट्स की अनुमानित सीमा तय करता है जिसके पार होते ही पढ़ना रुक जाता है, हालांकि सामान्य `readlines()` पूरी फाइल RAM में ले आता है।

4. Lazy File Iteration (for line in f) & Pointer Behavior (लेज़ी फाइल इटरेशन (for line in f) और कर्सर व्यवहार)

[EN] In Python, an opened file object is its own iterator, so `for line in f:` yields one line at a time lazily using efficient internal C buffering without creating a massive list in RAM. Therefore, `for line in f:` is strictly preferred over `for line in f.readlines():` when scanning large files. All three methods (`read`, `readline`, `readlines`) share and advance the exact same underlying file stream pointer: once `f.read()` reaches EOF, calling `f.readlines()` afterward returns `[]` unless `f.seek(0)` rewinds the cursor. To strip trailing line endings cleanly while reading, combine iteration with `line.rstrip('\n')` or use `f.read().splitlines()` for small files.

[HI] पायथन में फाइल ऑब्जेक्ट स्वयं एक इटरेटर होता है, इसलिए `for line in f:` बिना पूरी लिस्ट बनाए एक-एक पंक्ति लाता है और सबसे कम मेमोरी लेता है। इसी कारण `for line in f.readlines():` की तुलना में `for line in f:` को हमेशा प्राथमिकता दी जाती है। `read()`, `readline()` और `readlines()` तीनों एक ही फाइल पॉइंटर को आगे बढ़ाते हैं; यदि `read()` से फाइल अंत तक पढ़ ली गई हो, तो `seek(0)` के बिना `readlines()` खाली लिस्ट `[]` देगा। पंक्तियों के अंत से `'\n'` हटाने के लिए `line.rstrip('\n')` या छोटी फाइलों में `f.read().splitlines()` उपयोग किया जाता है।

Syntax, Formula & Technical Example (Reading Files: read(), readline(), readlines() Differences)

with open("sample.txt", "w+", encoding="utf-8") as f:
    f.write("Alpha\nBeta\nGamma")
    f.seek(0)
    print("read(5):", repr(f.read(5)))      # 'Alpha'
    f.seek(0)
    print("readline:", repr(f.readline()))  # 'Alpha\n'
    print("readlines:", f.readlines())      # ['Beta\n', 'Gamma']
    f.seek(0)
    print("stripped:", [ln.strip() for ln in f])

Reading Files: read(), readline(), readlines() Differences Quick Reference & Comparison Table

Reading MethodReturn Type & Trailing NewlineKey Exam Fact
f.read(n)Single str (or bytes); keeps '\n'Reads entire remaining file if n omitted; '' at EOF
f.readline(n)Single str ending in '\n'Blank line gives '\n' (truthy); EOF gives '' (falsy)
f.readlines(hint)list[str] preserving '\n'Empty file yields []; loads all lines into memory
for line in f:Lazy iterator yielding strMost memory-efficient idiom for multi-GB files

Reading Files: read(), readline(), readlines() Differences Top 20 Bilingual MCQs with Answers

Q1. What data type does `f.readlines()` return?

(`f.readlines()` किस डेटा टाइप में परिणाम लौटाता है?)

(A) list of strings

(B) tuple of strings

(C) generator object

(D) single concatenated string

Correct Answer: (A)

[EN] f.readlines() loads all lines into a Python `list` where each element is a `str`.

[HI] f.readlines() फाइल की सभी पंक्तियों को स्ट्रिंग्स की एक `list` के रूप में लौटाता है।

Q2. What does `f.readline()` return when it encounters a completely blank line in the middle of a text file?

(टेक्स्ट फाइल के बीच में एक खाली (blank) पंक्ति मिलने पर `f.readline()` क्या लौटाता है?)

(A) '' (empty string)

(B) '\n'

(C) ' ' (single space)

(D) None

Correct Answer: (B)

[EN] A blank line still contains its newline delimiter `'\n'`, which keeps it distinct from EOF `''`.

[HI] खाली पंक्ति के अंत में न्यूलाइन कैरेक्टर होता है, इसलिए `readline()` `'\n'` लौटाता है, जबकि EOF पर `''` मिलता है।

Q3. What does `f.readline()` return once the cursor has reached End of File (EOF)?

(फाइल के अंत (EOF) पर पहुंचने के बाद `f.readline()` कॉल करने पर क्या लौटता है?)

(A) '\n'

(B) EOFError exception

(C) None

(D) '' (empty string)

Correct Answer: (D)

[EN] At EOF, `read()` and `readline()` return `''` (empty string) in text mode without raising an exception.

[HI] EOF पर पहुंचने पर `readline()` और `read()` बिना किसी एरर के खाली स्ट्रिंग `''` लौटाते हैं।

Q4. In text mode (`'r'`, UTF-8), what does `f.read(5)` read?

(टेक्स्ट मोड (`'r'`, UTF-8) में `f.read(5)` क्या पढ़ता है?)

(A) Exactly 5 raw bytes regardless of multi-byte UTF-8 characters

(B) At most 5 characters (code points)

(C) 5 words separated by spaces

(D) Exactly 5 lines

Correct Answer: (B)

[EN] In text mode, the size parameter to `read(n)` counts decoded Unicode characters, whereas in binary mode it counts bytes.

[HI] टेक्स्ट मोड में `read(5)` अधिकतम 5 कैरेक्टर्स (अक्षर) पढ़ता है, जबकि बाइनरी मोड में 5 बाइट्स पढ़ता है।

Q5. Which approach is the most memory-efficient way to scan a 20 GB text log file in Python?

(पायथन में 20 GB की विशाल लॉग फाइल को प्रोसेस करने का सबसे कम मेमोरी वाला तरीका कौन-सा है?)

(A) for line in f.readlines():

(B) for line in f.read().split('\n'):

(C) for line in f:

(D) data = f.read()

Correct Answer: (C)

[EN] Iterating directly over the file object streams one line at a time lazily without loading the entire 20 GB into RAM.

[HI] `for line in f:` एक समय में केवल एक पंक्ति को RAM में लाता है, जबकि `readlines()` और `read()` पूरी 20 GB फाइल को मेमोरी में भर देते हैं।

Q6. Suppose `f` contains `'One\nTwo\nThree'`. After calling `f.read()`, what does an immediate call to `f.readlines()` return?

(मान लें `f` में `'One\nTwo\nThree'` है। `f.read()` चलाने के तुरंत बाद `f.readlines()` चलाने पर क्या मिलेगा?)

(A) ['Three']

(B) EOFError

(C) [] (empty list)

(D) ['One\n', 'Two\n', 'Three']

Correct Answer: (C)

[EN] f.read() moves the cursor all the way to EOF, so subsequent reads return empty results until `f.seek(0)` is called.

[HI] f.read() पॉइंटर को फाइल के अंत तक ले जाता है, इसलिए `seek(0)` के बिना अगली बार `readlines()` खाली लिस्ट `[]` लौटाता है।

Q7. What does `f.readlines()` return on a completely empty (0-byte) file?

(पूरी तरह खाली (0-बाइट) फाइल पर `f.readlines()` क्या लौटाता है?)

(A) ['\n']

(B) None

(C) []

(D) ['']

Correct Answer: (C)

[EN] With zero bytes in the file, `readlines()` immediately hits EOF and returns an empty list `[]`.

[HI] 0-बाइट की खाली फाइल पर `readlines()` खाली लिस्ट `[]` लौटाता है।

Q8. Given file contents `'Hello\nWorld'`, what does `f.readline()` return on its first call?

(यदि फाइल में `'Hello\nWorld'` लिखा है, तो पहली बार `f.readline()` कॉल करने पर क्या प्राप्त होगा?)

(A) ['Hello\n', 'World']

(B) 'H'

(C) 'Hello\n'

(D) 'Hello'

Correct Answer: (C)

[EN] `readline()` always includes the trailing `'\n'` character when present at the end of the line.

[HI] `readline()` पंक्ति के अंत में मौजूद `'\n'` को भी स्ट्रिंग के साथ शामिल करके `'Hello\n'` लौटाता है।

Q9. Given file contents `'PythonExam'`, what do two consecutive calls `f.read(3)` then `f.read(3)` return?

(यदि फाइल में `'PythonExam'` लिखा है, तो लगातार दो बार `f.read(3)` कॉल करने पर क्या लौटेगा?)

(A) 'Pyt' then 'hon'

(B) 'Pyt' then 'Pyt'

(C) 'Pyth' then 'onEx'

(D) 'Pyt' then 'honExam'

Correct Answer: (A)

[EN] Each `read(3)` advances the file cursor by 3 characters, so the second call picks up at index 3.

[HI] पहला `read(3)` `'Pyt'` पढ़कर कर्सर को 3 पर ले जाता है, और दूसरा `read(3)` आगे के `'hon'` को पढ़ता है।

Q10. What happens when passing a negative integer like `f.read(-5)` to `read()`?

(`f.read(-5)` जैसा ऋणात्मक पूर्णांक पास करने पर क्या होता है?)

(A) It reads the entire remaining file up to EOF

(B) It reads 5 characters backwards from the cursor

(C) ValueError: negative size not allowed

(D) It returns an empty string ''

Correct Answer: (A)

[EN] Any negative size (default `-1`) instructs Python's `read()` to read all remaining data until EOF.

[HI] कोई भी ऋणात्मक मान (जैसे `-1` या `-5`) देने पर `read()` फाइल के अंत तक पूरा डेटा पढ़ लेता है।

Q11. How does `f.read().splitlines()` differ from `f.readlines()`?

(`f.read().splitlines()` और `f.readlines()` में क्या अंतर है?)

(A) splitlines() reads only the first line

(B) splitlines() returns a tuple while readlines() returns a list

(C) readlines() strips '\n' automatically while splitlines() keeps '\n'

(D) splitlines() returns a list of lines WITHOUT trailing '\n' characters, whereas readlines() keeps them

Correct Answer: (D)

[EN] `str.splitlines()` splits on line boundaries and strips `\n` / `\r\n` by default, whereas `f.readlines()` preserves them.

[HI] `splitlines()` पंक्तियों की लिस्ट देता है लेकिन उनमें अंत का `'\n'` हटा देता है, जबकि `readlines()` में `'\n'` बना रहता है।

Q12. What does the optional `hint` parameter in `f.readlines(hint)` control?

(`f.readlines(hint)` में वैकल्पिक `hint` पैरामीटर क्या नियंत्रित करता है?)

(A) Stops reading additional lines once the total number of bytes/characters read exceeds hint

(B) The buffer encoding hint

(C) The maximum number of lines to read

(D) The starting line number to skip to

Correct Answer: (A)

[EN] If `hint > 0`, `readlines` reads full lines until the cumulative size read is greater than or equal to `hint`.

[HI] यदि `hint > 0` दिया हो, तो `readlines` उतनी ही पंक्तियाँ पढ़ता है जब तक कुल पढ़े गए बाइट्स/अक्षर `hint` से अधिक न हो जाएं।

Q13. If a line in a file is `'ABC\n'` (4 chars) and you call `f.readline(2)`, what is returned?

(यदि फाइल की एक पंक्ति `'ABC\n'` है और आप `f.readline(2)` कॉल करें, तो क्या लौटेगा?)

(A) 'AB\n'

(B) 'ABC\n'

(C) 'AB'

(D) ['A', 'B']

Correct Answer: (C)

[EN] The `size` parameter in `readline(size)` limits the read to at most `size` characters even before reaching `'\n'`.

[HI] `readline(2)` अधिक से अधिक 2 अक्षर `'AB'` ही पढ़ता है और बाकी `'C\n'` अगली रीड के लिए छोड़ देता है।

Q14. Why might `f.readlines()[-1]` lack a `'\n'` at the end while earlier elements have `'\n'`?

(`f.readlines()[-1]` में अंत में `'\n'` क्यों अनुपस्थित हो सकता है जबकि बाकी तत्वों में `'\n'` होता है?)

(A) Because lists cannot store strings ending in '\n' at the last index

(B) If the file itself does not end with a trailing newline character on disk

(C) Because readlines() converts the last line using strip()

(D) Because Python always strips '\n' from the last element of readlines()

Correct Answer: (B)

[EN] `readlines()` preserves exact file line breaks; if the final line on disk ends at EOF with no newline, no `'\n'` appears.

[HI] यदि फाइल के अंतिम अक्षर के बाद डिस्क पर न्यूलाइन न हो, तो `readlines()` के अंतिम तत्व में भी `'\n'` नहीं होगा।

Q15. What is the cleanest way to strip only the trailing newline from each line while iterating `for line in f:` without stripping leading spaces?

(`for line in f:` चलाते समय शुरुआती स्पेस बचाए रखते हुए केवल अंत का न्यूलाइन हटाने का सबसे सटीक तरीका क्या है?)

(A) line.rstrip('\r\n')

(B) line.strip()

(C) line.lstrip('\n')

(D) line.replace(' ', '')

Correct Answer: (A)

[EN] `strip()` removes leading/trailing spaces and tabs too, whereas `rstrip('\r\n')` removes only line-break characters on the right.

[HI] `strip()` आगे के स्पेस भी हटा देता है, जबकि `rstrip('\r\n')` केवल दाईं ओर का न्यूलाइन हटाता है।

Q16. Which statement is NOT true about `read()`, `readline()`, and `readlines()`?

(`read()`, `readline()` और `readlines()` के बारे में निम्न में से कौन-सा कथन सत्य नहीं है?)

(A) All three methods advance the current file stream position

(B) f.readlines() automatically strips '\n' from every line and returns a tuple

(C) f.readline() returns '\n' for an empty line and '' at EOF

(D) f.read() returns a single string containing the entire file in text mode

Correct Answer: (B)

[EN] `f.readlines()` returns a `list` (not a tuple) and keeps the `'\n'` character attached to each line.

[HI] `f.readlines()` टपल नहीं बल्कि `list` लौटाता है और प्रत्येक पंक्ति के अंत में `'\n'` को हटाता नहीं है।

Q17. Within Reading Files: read(), readline(), readlines() Differences, which reading method directly maps to: "Single str (or bytes); keeps '\n'"?

(Reading Files: read(), readline(), readlines() Differences में कौन सा Reading Method सीधे "Single str (or bytes); keeps '\n'" से संबंधित है?)

(A) for line in f:

(B) f.readlines(hint)

(C) f.read(n)

(D) f.readline(n)

Correct Answer: (C)

[EN] In Reading Files: read(), readline(), readlines() Differences, 'f.read(n)' handles 'Single str (or bytes); keeps '\n'' (Reads entire remaining file if n omitted; '' at EOF).

[HI] Reading Files: read(), readline(), readlines() Differences में 'f.read(n)' का कार्य/विवरण 'Single str (or bytes); keeps '\n'' (Reads entire remaining file if n omitted; '' at EOF) है।

Q18. Which option accurately describes 'f.readline(n)' in Reading Files: read(), readline(), readlines() Differences?

(Reading Files: read(), readline(), readlines() Differences के संदर्भ में 'f.readline(n)' की सही विशेषता कौन सी है?)

(A) list[str] preserving '\n'

(B) Single str ending in '\n'

(C) Single str (or bytes); keeps '\n'

(D) Lazy iterator yielding str

Correct Answer: (B)

[EN] 'f.readline(n)' provides 'Single str ending in '\n'' — key point: Blank line gives '\n' (truthy); EOF gives '' (falsy).

[HI] 'f.readline(n)' का मुख्य विवरण 'Single str ending in '\n'' है (Blank line gives '\n' (truthy); EOF gives '' (falsy))।

Q19. In Reading Files: read(), readline(), readlines() Differences, identify the correct parameter for the specification: "list[str] preserving '\n'".

(Reading Files: read(), readline(), readlines() Differences में "list[str] preserving '\n'" विवरण किस विकल्प के लिए सही है?)

(A) f.readlines(hint)

(B) f.read(n)

(C) for line in f:

(D) f.readline(n)

Correct Answer: (A)

[EN] 'f.readlines(hint)' corresponds to 'list[str] preserving '\n'' (Empty file yields []; loads all lines into memory).

[HI] 'f.readlines(hint)' का संबंध 'list[str] preserving '\n'' (Empty file yields []; loads all lines into memory) से है।

Q20. Considering Reading Files: read(), readline(), readlines() Differences, what key behavior defines 'for line in f:'?

(Reading Files: read(), readline(), readlines() Differences में 'for line in f:' की मुख्य भूमिका या मान क्या है?)

(A) Single str (or bytes); keeps '\n'

(B) list[str] preserving '\n'

(C) Single str ending in '\n'

(D) Lazy iterator yielding str

Correct Answer: (D)

[EN] 'for line in f:' represents 'Lazy iterator yielding str' (Most memory-efficient idiom for multi-GB files).

[HI] 'for line in f:' का अर्थ/मान 'Lazy iterator yielding str' है (Most memory-efficient idiom for multi-GB files)।

Reading Files: read(), readline(), readlines() Differences — Exam FAQs

Q1: How does a `while` loop using `f.readline()` distinguish a blank line from End of File?

`f.readline()` का उपयोग करने वाला `while` लूप खाली पंक्ति और फाइल के अंत (EOF) में अंतर कैसे करता है?

[EN] A blank line inside a file contains a newline character, so `f.readline()` returns `'\n'`, which has length 1 and evaluates to `True` in Python. At EOF, `f.readline()` returns `''` (empty string, length 0), which evaluates to `False` and stops the loop.

[HI] फाइल के भीतर की खाली पंक्ति में न्यूलाइन कैरेक्टर मौजूद रहता है, इसलिए `readline()` `'\n'` (Truthful) लौटाता है। EOF पर `''` (Falsy) मिलने पर लूप रुक जाता है।

Q2: Is `for line in f.readlines():` functionally identical to `for line in f:`?

क्या `for line in f.readlines():` और `for line in f:` बिल्कुल एक समान काम करते हैं?

[EN] They yield the same lines in small files, but `f.readlines()` loads every line into a list in memory up front, risking crashes on large files. `for line in f:` streams lines lazily one by one using constant memory.

[HI] छोटी फाइलों में आउटपुट समान दिखता है, लेकिन `f.readlines()` पूरी फाइल की लिस्ट पहले RAM में बनाता है। बड़ी फाइलों में `for line in f:` एक-एक पंक्ति पढ़कर मेमोरी बचाता है।

Q3: What happens if you call `next(f)` on an opened file object after reading everything?

फाइल पूरी पढ़े जाने के बाद फाइल ऑब्जेक्ट पर `next(f)` कॉल करने पर क्या होता है?

[EN] Unlike `f.readline()` which returns `''` at EOF, calling `next(f)` on an exhausted file iterator raises `StopIteration`, which is how `for line in f:` knows when to terminate.

[HI] `f.readline()` के विपरीत जो EOF पर `''` लौटाता है, इटरेटर समाप्त होने पर `next(f)` कॉल करने से `StopIteration` एक्सेप्शन आता है जिससे `for` लूप समाप्त होता है।

Related Posts

  • Loading related posts...

Post a Comment

Search Topic Notes & 20 MCQs (Hindi / English)