📌 Snapshot
- Persistent storage (files) is needed because variables lose their values after program execution ends.
- There are two fundamental file types — text and binary — and each stores data internally using byte sequences.
- A file in Python has a complete lifecycle: open → read/write → seek/tell → close, using the
iomodule's built-in functions. - The
withclause is a safer, auto-closing alternative to explicitopen()/close()calls. - The
picklemodule serializes and de-serializes Python objects (pickling/unpickling) into binary files — a topic NTA has targeted with direct and application-based questions.
📖 Detailed Notes
2.1 Core concepts
- What is a file? A file is a named location on a secondary storage media where data are permanently stored for later access. Programs written in script mode are stored with a
.pyextension; data output can also be stored permanently in a file. (NCERT §2.1, p. 19) - Why files are needed: Variables in a program have a lifetime only till the program is under execution. To reuse input data or generated output (e.g., employee information, inventory, sales), data must be stored permanently on secondary storage devices. (NCERT §2.1, p. 19)
- Text files: A text file is a sequence of characters consisting of alphabets, numbers, and other special symbols. Extensions like
.txt,.py,.csvare examples. Internally, characters are stored as bytes using ASCII, UNICODE, or another encoding scheme. Each line is terminated by a special End of Line (EOL) character; in Python the default EOL is the newline character\n. (NCERT §2.2.1, p. 20) - Binary files: Binary files are stored in terms of bytes (0s and 1s) that represent actual content such as images, audio, video, compressed files, and executable files. They are not human-readable; opening one in a text editor yields garbage values. A single bit change can corrupt a binary file. Specific software is required to read or write binary file contents. (NCERT §2.2.2, p. 21)
- Opening a file —
open(): Syntax isfile_object = open(file_name, access_mode). The function returns a file handle stored infile_object. Thefile_objecthas attributes:<file.closed>(True if closed),<file.mode>(access mode),<file.name>(file name). If the file does not exist,open()in write mode creates a new empty file. (NCERT §2.3.1, p. 21–22) - File access modes (Table 2.1): Key modes —
r(read-only, offset at beginning),rb(binary read-only),r+or+r(read and write, beginning),w(write, overwrites existing content or creates new file),wb+or+wb(read, write, binary),a(append, offset at end; creates file if absent),a+or+a(append and read, offset at end). Default mode is read (r); default file type is text. (NCERT §2.3.1, p. 22) - Closing a file —
close(): Syntax:file_object.close(). Frees memory allocated to the file. Python flushes any unwritten/unsaved data to the file before closing. If a file object is re-assigned to another file, the previous file is automatically closed. (NCERT §2.3.2, p. 23) withclause: Syntax:with open(file_name, access_mode) as file_object:. The file is closed automatically when control exits thewithblock, even if an exception occurs. No explicitclose()is needed. (NCERT §2.3.3, p. 23)- Writing —
write(): Takes a single string argument and writes it to the text file. Returns the number of characters written. Numeric data must be converted to string usingstr()before writing. A\nmust be added manually to mark end of line.write()actually writes data onto a buffer; the buffer is moved to permanent storage only whenclose()is called (orflush()is explicitly invoked). (NCERT §2.4.1, p. 24) - Writing —
writelines(): Writes a sequence of strings (from an iterable such as a list or tuple). Does not return the number of characters written. Does not add newline characters automatically. (NCERT §2.4.2, p. 24–25) - Reading —
read([n]): Reads and returnsnbytes from the file. If no argument or a negative number is given, the entire file content is read and returned as a single string. (NCERT §2.5.1, p. 25) - Reading —
readline([n]): Reads one complete line (up to and including\n) from the file. Ifnis specified, reads at mostnbytes from that line. Returns an empty string at EOF. Useful for iterating line by line with a loop. (NCERT §2.5.2, p. 26) - Reading —
readlines(): Reads all lines from the file and returns them as a list of strings, each ending with\n.split()separates words within a line;splitlines()returns each line as a list element without the newline character. (NCERT §2.5.3, p. 26–27) tell(): Returns an integer giving the current byte position of the file object from the beginning of the file. Syntax:file_object.tell(). (NCERT §2.6.1, p. 28)seek(): Positions the file object at a specified location. Syntax:file_object.seek(offset [, reference_point]).reference_pointvalues:0= beginning (default),1= current position,2= end of file.offsetis the number of bytes to move. (NCERT §2.6.2, p. 28)- Creating and traversing a text file (§2.7): Combining
open()inw+mode,write(),seek(0), andread()allows a single program to both write and read data. Usingreadline()in awhileloop traverses the file line by line until an empty string (EOF) is returned. (NCERT §2.7, p. 29–31) - Pickle module — serialization: Python's
picklemodule serializes (pickles) any Python object (list, tuple, dictionary, etc.) into a byte stream that can be stored in a binary file or sent over a network. The reverse process — converting the byte stream back to a Python object — is called de-serialization or unpickling. Thepicklemodule must be imported explicitly. (NCERT §2.8, p. 32) dump(): Syntax:pickle.dump(data_object, file_object). Converts (pickles) a Python object and writes it to a binary file opened inwborabmode. (NCERT §2.8.1, p. 32)load(): Syntax:store_object = pickle.load(file_object). Reads (unpickles) a Python object from a binary file opened inrbmode. At end-of-file, raisesEOFError, which can be caught with atry…exceptblock. (NCERT §2.8.2, p. 33)
2.2 Definitions to memorise
| Term | Definition | Page |
|---|---|---|
| File | A named location on a secondary storage media where data are permanently stored for later access. | 19 |
| Text file | A file that consists of human-readable characters (alphabets, numbers, special symbols) stored as ASCII/UNICODE bytes; lines are separated by EOL (\n). |
20 |
| Binary file | A file that stores data as a stream of bytes representing actual content (images, audio, executables, etc.); not human-readable. | 21 |
File handle (file_object) |
The object returned by open(); establishes a link between the program and the data file on permanent storage. |
21 |
| Access mode | An optional argument to open() that specifies how the file is to be processed (read, write, append, binary, etc.). |
22 |
| EOL (End of Line) | A special character that terminates each line of a text file; default in Python is \n. |
20 |
| Serialization (Pickling) | The process of transforming a Python object in memory to a byte stream (stored in a binary file or sent over a network). Also called pickling. | 32 |
| De-serialization (Unpickling) | The inverse of pickling; converting a byte stream back to a Python object. | 32 |
seek() |
A method that repositions the file object to a specified byte offset from a reference point (0 = beginning, 1 = current, 2 = end). | 28 |
tell() |
A method that returns the current byte position of the file object from the beginning of the file. | 28 |
with clause |
A Python construct for opening files that automatically closes the file when the block exits, even on exceptions. | 23 |
flush() |
A method that forcefully writes buffer contents to the file without closing it. | 24 |
open() |
Built-in function that opens a file and returns a file object | 21 |
close() |
File method that flushes the buffer and frees the file resources | 23 |
write() |
File method that writes a single string to a text file | 24 |
writelines() |
File method that writes an iterable of strings | 24 |
read([n]) |
File method that returns n bytes (entire file if no argument) | 25 |
readline([n]) |
File method that reads one line up to n bytes | 26 |
readlines() |
File method that reads all lines into a list | 26 |
pickle.dump() |
Pickle function that serializes a Python object into a binary file | 32 |
pickle.load() |
Pickle function that deserializes a Python object from a binary file | 33 |
EOFError |
Exception raised by pickle.load() when end of file is reached |
33 |
wb mode |
Binary write mode — required for pickle.dump() |
32 |
rb mode |
Binary read mode — required for pickle.load() |
33 |
| Buffer | In-memory holding area for data before it is written to disk | 24 |
2.3 Diagrams / processes to remember
- Table 2.1 — File Open Modes (p. 22): A tabular summary of all access modes (
r,rb,r+,w,wb+,a,a+) with their descriptions and initial file offset positions. Students must memorize which modes start at the beginning vs. the end of the file, and which modes overwrite vs. append. - Figure 2.1 — Contents of myfile.txt (p. 25): Shows the output of
writelines()in Notepad — three lines written without explicit\nseparators display correctly only because\nwas embedded in each string. Reinforces thatwritelines()does not auto-insert newlines. - Program 2-2 — seek() and tell() demonstration (p. 28–29): Illustrates the file object moving from byte 33 (after
read()) back to 0 (afterseek(0)) and then to byte 10 (afterseek(10)). Key to understanding random access. - Program 2-8 — Binary file with pickle (p. 34–35): Shows the complete workflow — import pickle → open in
abmode →dump()records → close → open inrbmode →load()records in atry…except EOFErrorloop. The output shows each employee record loaded as a list.
2.4 Common confusions / NTA trap points
write()vswritelines():write()accepts only a single string and returns the character count;writelines()accepts an iterable of strings and returnsNone. Neither method automatically adds\n— the student must include it. NTA often gives code snippets and asks what the output or return value will be.- Default file mode and type: If no access mode is specified in
open(), Python opens the file in read (r) text mode. Many MCQs test whether students know thatwtruncates existing content whileapreserves it. read()with no argument vsreadline():read()with no argument reads the entire file as one string;readline()reads exactly one line including the\n. Confusing the two leads to wrong answers in code-trace questions.seek()reference point values: 0 = beginning, 1 = current position, 2 = end. NTA likes distractor options that swap these values or claim the default reference point is 1 instead of 0.- Pickle file modes:
dump()requires the file to be opened in binary write (wb) or binary append (ab) mode;load()requires binary read (rb) mode. Opening a pickle file in text mode (worr) is a common trap. withclause auto-close (NCERT §2.3.3, p. 23). Students sometimes think the file remains open after thewithblock. The file is automatically closed when the block exits.wmode truncates! (NCERT Table 2.1, p. 22). Opening an existing file inwdeletes its contents. Useato preserve and append. NTA exploits this.open()without mode defaults tortext (NCERT §2.3.1, p. 22). NTA distractor: claims default isw.- EOF in
readline()returns empty string, not None (NCERT §2.5.2, p. 26). Usewhile line := readline():style or test for''. pickle.dump()writes ONE object per call (NCERT §2.8.1, p. 32). To store multiple, call dump in a loop.tell()returns BYTES not lines (NCERT §2.6.1, p. 28). It is a byte offset.seek()reference_point in text mode (NCERT §2.6.2, p. 28). For text files, NCERT recommends onlyseek(offset, 0)— moving by negative offsets in text mode can be problematic.
🎯 Practice MCQs
First 3 questions free · create a free account to unlock the rest — answers & explanations included, no payment needed
Q1. Which of the following is the correct syntax to open a file named `data.txt` for both reading and writing, with the file offset positioned at the beginning of the file?
▸ Show answer & explanation
Answer: B
`r+` (or `+r`) opens the file in both read and write mode with the file offset at the beginning. `a+` opens in append and read mode with the offset at the end of the file, and `w` overwrites all existing content. ---
Q2. Consider the following code: ```python myobject = open("myfile.txt", "w") myobject.write("Hello World\n") myobject.close() ``` Which of the following statements is TRUE about the `write()` call above?
▸ Show answer & explanation
Answer: B
`write()` places data in a buffer; permanent storage is updated only when `close()` (or `flush()`) is called. `write()` also returns the number of characters written — not `None` — making option C incorrect. ---
Q3. What will be the output of the following code, assuming `myfile.txt` contains the three lines: `Hello everyone`, `Writing multiline strings`, `This is the third line`? ```python myobject = open("myfile.txt", "r") print(myobject.readlines()) myobject.close() ```
▸ Show answer & explanation
Answer: C
`readlines()` returns a **list** (not a tuple) of strings where each element retains its trailing `\n`. The last line may not have `\n` if the file does not end with one, which is why the third element has no `\n`. ---
🔒 11 more practice MCQs
Create a free account to unlock every MCQ in this chapter — answers and explanations included. No payment needed.
Already registered? Just log in and they'll all appear here.
Q4. Match the following file methods with their correct descriptions: | Method | Description | |---|---| | P. `tell()` | 1. Reads one complete line including the newline character | | Q. `seek()` | 2. Returns the current byte position of the file object | | R. `readline()` | 3. Repositions the file object to a specified byte offset | | S. `read()` | 4. Reads the entire file content as a single string when called with no argument |
▸ Show answer & explanation
Answer: B
`tell()` returns current byte position (P-2); `seek()` repositions the file object (Q-3); `readline()` reads one complete line (R-1); `read()` with no argument reads entire file (S-4). ---
Q5. **Assertion (A):** Using the `with` clause to open a file in Python eliminates the need to call `close()` explicitly. **Reason (R):** The `with` clause automatically closes the file once the control moves outside the `with` block, even if an exception occurs during execution.
▸ Show answer & explanation
Answer: A
R directly explains why A is true — the automatic closure on exiting the `with` block (even on exceptions) is precisely what removes the need for an explicit `close()` call. ---
Q6. Which of the following statements about binary files in Python are CORRECT? 1. Binary files store data as a stream of bytes and are not human-readable. 2. Binary files can be opened and read correctly using any standard text editor like Notepad. 3. Even a single bit change in a binary file can corrupt it and make it unreadable by the supporting application. 4. Python programs can both read and write binary files.
▸ Show answer & explanation
Answer: B
Statement 2 is false — opening a binary file in a text editor shows garbage values. Statements 1, 3, and 4 are explicitly stated in the NCERT chapter. ---
Q7. The `seek()` method is called as `fileobject.seek(10, 0)` on an open file. What does this statement do?
▸ Show answer & explanation
Answer: B
In `seek(offset, reference_point)`, a `reference_point` of `0` means the beginning of the file. So `seek(10, 0)` positions the file object at the 10th byte from the beginning. A `reference_point` of `1` would indicate the current position, and `2` the end of the file. ---
Q8. Which mode opens a file for reading and writing without truncating?
▸ Show answer & explanation
Answer: C
Q9. Output: ```python f = open('a.txt', 'w') f.write("Hi") f.close() f = open('a.txt', 'a') f.write("Bye") f.close() print(open('a.txt').read()) ```
▸ Show answer & explanation
Answer: C
Append mode preserves "Hi" and adds "Bye". ---
Q10. Which method returns the current byte position of the file pointer?
▸ Show answer & explanation
Answer: B
Q11. `pickle.load()` raises which exception at end of file?
▸ Show answer & explanation
Answer: B
Q12. The default value of `reference_point` in `seek()` is:
▸ Show answer & explanation
Answer: A
Q13. Assertion (A): A binary file cannot be opened with Notepad to read its contents. Reason (R): Binary files store data as raw bytes that do not correspond to printable characters in any encoding.
▸ Show answer & explanation
Answer: A
Q14. Output of `writelines(['a','b','c'])` on a fresh file followed by `read()`:
▸ Show answer & explanation
Answer: B
writelines does NOT auto-insert newlines.
📊 Previous-Year Questions
Practise with real CUET Computer Science previous-year papers — every question solved, with the correct answer and a step-by-step explanation.
View solved CUET PYQ papers →Ready to drill Computer Science?
Unlock all MCQs, chapter tests, mocks & PYQs for ₹199/year.
Get UniDrill Pro