Class 12 Computer Science – Chapter 2: File Handling in Python (200+ MCQs with Detailed Explanation)
Welcome to Mohan Exam, your trusted platform for NCERT-based and exam-oriented learning.
In this post, we bring you 200+ carefully crafted MCQs from Class 12 Computer Science – Chapter 2: File Handling in Python, designed to cover every important topic and concept of the chapter in a clear, concise, and exam-focused way.
Each question comes with a detailed explanation, helping you not only find the correct answer but also understand the logic behind it.
This MCQ series includes all key concepts — from open(), read(), and write() to advanced topics like seek(), tell(), and the pickle module — ensuring a complete and effortless understanding of Python File Handling.
With this collection, you will be able to:
- Revise the entire NCERT syllabus in a structured way
- Strengthen conceptual clarity through real coding examples
- Prepare confidently for board exams and competitive tests
At Mohan Exam, our mission is simple — to make learning clear, practical, and exam-smart.
If at any point you feel there is any scope for improvement or correction, we truly welcome your valuable feedback. Your suggestions help us maintain the highest quality of educational content for every learner.
To get MCQs of all chapters of Class 12 Computer Science, visit our website Mohan Exam or click on the link below
Explore All Class 12 Computer Science MCQs on Mohan Exam
1. In Python, a file is best described as:
A. A temporary variable used for storing input
B. A named location on secondary storage media where data is permanently stored
C. A memory address for storing volatile data
D. A directory containing multiple files
Answer: B. A named location on secondary storage media where data is permanently stored
Explanation
Explanation:
A file in Python (or any operating system) is a named storage location on a secondary storage device such as a hard disk, SSD, or flash drive.
It allows permanent storage of data, which means that the data remains even after the program execution ends — unlike variables stored in RAM, which are erased when the program stops.Python provides built-in support for file handling through functions like
open(),read(),write(), andclose(). These enable reading from and writing to files in both text and binary formats.
2. What is the main limitation of storing data only in variables in a Python program?
A. Variables can store only numbers
B. Variables get deleted after program execution ends
C. Variables cannot store strings
D. Variables require file permission to access
Answer: B. Variables get deleted after program execution ends
Explanation
Explanation:
Variables in Python are stored in the main memory (RAM), which is volatile in nature.
This means that once a Python program finishes execution or the system shuts down, all the data stored in variables is automatically erased.Hence, if you want your data to remain available after the program ends, you must store it in a file (text or binary) or a database.
This is the main reason file handling is introduced — to achieve data persistence (permanent storage).For example:
name = "Mohan" print(name) # After program ends, 'name' is deleted from memoryTo make it permanent:
f = open("data.txt", "w") f.write("Mohan") f.close()Now, “Mohan” is stored permanently in the file
data.txt.
3. Files help in achieving which of the following?
A. Temporary memory usage
B. Data persistence and reusability
C. Faster execution
D. Only text data storage
Answer: B. Data persistence and reusability
Explanation
Explanation:
Files in Python (or any programming language) are used to store data permanently on a secondary storage device (like HDD or SSD).Key Points:
- Data Persistence: Unlike variables stored in RAM (which are temporary), data in files remains after program execution ends.
- Reusability: Once stored, data in files can be read and used multiple times by the same or different programs.
- Avoids Repetitive Input: Users don’t need to re-enter the same data every time the program runs.
Files can store both text and binary data, so they are not limited to only text.
Example in Python:
# Writing data to file f = open("student.txt", "w") f.write("Name: Mohan\nAge: 18") f.close() # Reading data later f = open("student.txt", "r") print(f.read()) f.close()Here, data is persistent and can be reused anytime by reading the file.
4. In Python, programs written in script mode are saved with which extension?
A. .py
B. .txt
C. .docx
D. .csv
Answer: A. .py
Explanation
Explanation:
Python programs written in script mode are saved as source code files.
- The
.pyextension indicates that the file contains Python code.- When you run a
.pyfile, the Python interpreter reads the file and executes the code.- Other file extensions like
.txtor.csvare not executable Python scripts; they are treated as data files.Example:
# Save this as hello.py print("Hello, World!")Running this script using:
python hello.pywill execute the code and print:
Hello, World!
5. How are files stored on a computer internally?
A. As a sequence of characters
B. As a sequence of bytes (0s and 1s)
C. As text paragraphs
D. As encoded audio signals
Answer: B. As a sequence of bytes (0s and 1s)
Explanation
Explanation:
- Internally, all files on a computer—whether text, images, audio, or video—are stored as a sequence of bytes (each byte is 8 bits).
- The computer interprets these bytes differently depending on the file type:
- Text files: Bytes are interpreted as characters using an encoding standard (e.g., ASCII, UTF-8).
- Binary files: Bytes may represent images, audio, executable instructions, etc.
- This uniform representation allows the computer to handle any type of file consistently at the hardware level.
Example:
- Text file
"hello.txt": stored as bytes corresponding to ASCII codes forh,e,l,l,o.- Image file
"photo.jpg": stored as binary bytes that the image viewer interprets according to JPEG format.
6. What are the two main types of data files in Python?
A. Text file and Binary file
B. Audio file and Video file
C. CSV file and DOC file
D. HTML file and XML file
Answer: A. Text file and Binary file
Explanation
Explanation:
Python primarily works with two types of data files:
- Text Files:
- Contain human-readable characters.
- Examples:
.txt,.py,.csv.- Can be read and edited with a text editor.
- Python reads/writes text files using default encoding (like UTF-8).
f = open("example.txt", "w") f.write("Hello, World!") f.close()- Binary Files:
- Contain non-human-readable bytes.
- Examples:
.dat,.bin,.jpg,.mp3.- Used for images, audio, executable files, or any non-text data.
- Python reads/writes binary files using
"rb"(read binary) or"wb"(write binary) modes.f = open("example.bin", "wb") f.write(b"\x00\x01\x02") f.close()Summary: Text files are readable and editable; binary files are for efficient storage and machine-readable data.
7. Which of the following statements about text files is correct?
A. They contain non-human readable data
B. They can be opened by any text editor like Notepad
C. They require special programs to open
D. They store images and audio
Answer: B. They can be opened by any text editor like Notepad
Explanation
Explanation:
Text files are files that contain data stored as human-readable characters, usually encoded in ASCII or Unicode (UTF-8) format.Key points:
- Text files can be opened and edited using any text editor such as Notepad, VS Code, Sublime Text, or IDLE.
- They store data in plain text — for example, words, numbers, or symbols.
- Python programs often use text files (
.txt,.py,.csv) for storing readable information.- When opened, the text is directly visible and understandable to humans.
Example in Python:
f = open("notes.txt", "w") f.write("Python is fun!") f.close() # This file can be opened in Notepad and will show: Python is fun!Text files differ from binary files, which contain data in byte form (not directly readable).
8. Which of the following file extensions generally represent text files?
A. .exe, .dll
B. .jpg, .png
C. .txt, .py
D. .bin, .dat
Correct Answer: C. .txt, .py
Explanation
Explanation:
Text files are those that contain human-readable characters and can be opened using simple text editors such as Notepad, VS Code, or IDLE.Common text file extensions include:
.txt→ Plain text file (simple readable text).py→ Python source code file (also text-based).csv→ Comma Separated Values file (data in table form).html→ Webpage source file (HTML code, readable text format)On the other hand:
.exe,.dllare binary/executable files..jpg,.pngare image (binary) files..bin,.datare pure binary data files.Example:
f = open("example.txt", "w") f.write("This is a text file.") f.close()The file
example.txtcan be opened in any text editor and read easily.
9. Binary files are different from text files because:
A. They can be read by any editor
B. They are stored in human-readable characters
C. They are made up of symbols and non-human-readable data
D. They always contain ASCII text
Answer: C. They are made up of symbols and non-human-readable data
Explanation
Explanation:
Binary files store data in the form of bytes (0s and 1s) — not in human-readable characters.
This means that when you open a binary file in a text editor like Notepad, you’ll see unreadable symbols or gibberish, because the data is encoded for machines, not for human interpretation.Key Differences:
Aspect Text File Binary File Readability Human-readable Machine-readable Storage format Characters (ASCII/Unicode) Bytes (0s and 1s) Examples .txt,.py,.csv.dat,.bin,.jpg,.exeOpening Can be opened by text editor Needs special program (e.g., image viewer, audio player) Example in Python:
# Writing binary data f = open("data.bin", "wb") f.write(b'\x42\x79\x74\x65\x73') # Writing bytes f.close()Opening
data.binin a text editor will show symbols like “Bytës” or gibberish, not readable text.
10. When we open a text file, what actually happens internally?
A. Python converts text into Unicode values stored as bytes
B. The file is stored temporarily in cache
C. Each character is converted to hexadecimal values
D. The file is copied to memory in plain text format
Answer: A. Python converts text into Unicode values stored as bytes
Explanation
Explanation:
When a text file is opened in Python (usingopen()), the data in the file is read or written as text, but internally, Python stores and processes this data as Unicode characters represented in bytes form.Here’s what happens step-by-step:
- Each character in the text file (like
'A','b','3', etc.) is represented by a Unicode code point.- These code points are then encoded into bytes (using encodings such as UTF-8 or ASCII) before being stored on disk.
- When reading the file, Python decodes the bytes back into characters, making it human-readable again.
Example:
# Writing to a text file f = open("demo.txt", "w", encoding="utf-8") f.write("Hello") f.close() # Internally, 'Hello' is stored as bytes: 72 101 108 108 111So even though the file appears to contain text, the computer actually stores it as a sequence of bytes (0s and 1s) corresponding to Unicode values.
11. In computing, how is every file stored internally on a computer?
A. As a list of characters
B. As a sequence of bytes (0s and 1s)
C. As text paragraphs
D. As Unicode strings
Answer: B. As a sequence of bytes (0s and 1s)
Explanation
Explanation:
Every file in a computer system — whether it’s a text file, image, audio, or video — is stored internally as binary data, i.e., a sequence of bytes (0s and 1s).
These bytes are interpreted differently depending on the file type and encoding scheme. For example:
- Text files use encodings like ASCII or UTF-8,
- Image or audio files use binary formats specific to their type.
12. Which of the following statements correctly differentiates between text files and binary files?
A. Both contain human-readable characters
B. Text files contain human-readable data, while binary files contain non-human-readable data
C. Binary files can be opened in Notepad
D. Text files always require special software to access
Answer: B. Text files contain human-readable data, while binary files contain non-human-readable data
Explanation
Explanation:
- Text files store data as a sequence of characters using encodings such as ASCII or UTF-8.
→ They can be opened easily in text editors like Notepad or VS Code.- Binary files, on the other hand, store data in machine-readable (0s and 1s) form.
→ They can only be interpreted correctly by the specific program that created them (e.g., images, audio, videos, etc.).Examples:
- Text file:
.txt,.py,.csv- Binary file:
.exe,.jpg,.dat“Text files contain data in character form which can be read easily, while binary files contain data in machine-readable form.”
13. Which of the following extensions are commonly used for text files in Python?
A. .jpg, .png
B. .txt, .py, .csv
C. .exe, .dll
D. .bin, .dat
Answer: B. .txt, .py, .csv
Explanation
Explanation:
Text files in Python store data in human-readable character format (ASCII or Unicode).
Common text file extensions include:
.txt→ Plain text file.py→ Python source code file.csv→ Comma-Separated Values file (text-based data storage)These files can be opened easily in text editors like Notepad, VS Code, or even Excel (for
.csv).“Examples of text files include .txt, .py, and .csv files that contain data in readable character form.”
14. When a text file is opened using a text editor, how does it display readable text?
A. The text editor converts ASCII values into human-readable characters
B. The text editor executes the binary data directly
C. The text editor removes all non-printable bytes
D. The text editor compresses the data for display
Answer: A. The text editor converts ASCII values into human-readable characters
Explanation
Explanation:
When a text file is opened in an editor (like Notepad or VS Code), the file’s contents — which are stored as byte values representing characters — are decoded using a specific character encoding scheme (such as ASCII or UTF-8).
This decoding process converts numeric byte values into human-readable characters (letters, digits, symbols, etc.).For example:
- The ASCII code 65 corresponds to the character ‘A’.
- The ASCII code 97 corresponds to ‘a’.
Thus, what you see as readable text is actually the decoded representation of stored byte data.
“A text file stores data as a sequence of characters that represent their ASCII or Unicode values, which text editors can directly interpret and display.”
15. In ASCII encoding, which number represents the capital letter ‘A’?
A. 60
B. 65
C. 70
D. 97
Answer: B. 65
Explanation
Explanation:
- ASCII (American Standard Code for Information Interchange) assigns unique numeric codes to characters.
- In ASCII:
- 65 →
'A'(capital A)- 97 →
'a'(small a)- 48–57 → digits
'0'to'9'Each ASCII value can also be represented in binary. For example:
65 in decimal = 1000001 in binaryPython example:
print(ord('A')) # Output: 65 print(chr(65)) # Output: 'A'Here,
ord()returns the ASCII/Unicode code of a character, andchr()converts a number to its corresponding character.
16. What is the purpose of the End of Line (EOL) character in a text file?
A. To indicate the end of the file
B. To represent a space
C. To mark the end of a line and start a new one
D. To separate different file formats
Answer: C. To mark the end of a line and start a new one
Explanation
Explanation:
- The End of Line (EOL) character in a text file is used to signal the end of the current line and move the cursor to the beginning of the next line.
- Different operating systems use different EOL characters:
- Windows:
\r\n(Carriage Return + Line Feed)- Unix/Linux/MacOS:
\n(Line Feed)- In Python, when reading or writing files, EOL characters help separate lines for proper display or processing.
Example in Python:
f = open("example.txt", "w") f.write("Hello\nWorld") f.close() f = open("example.txt", "r") print(f.read()) f.close()Output:
Hello WorldHere,
\nis the EOL character that moves the text to a new line.
17. What is the default End of Line (EOL) character used in Python text files?
A. \t
B. \n
C. \s
D. \\
Answer: B. \n
Explanation
Explanation:
- In Python, the default End of Line (EOL) character for text files is the newline character
\n.- When writing or reading text files, Python interprets
\nas a signal to move to the next line.- Python automatically translates the newline character based on the operating system when opening files in text mode (
'r'or'w'):
- Windows: Converts
\nto\r\nin the file- Unix/Linux/MacOS: Keeps
\nas isExample in Python:
f = open("example.txt", "w") f.write("Line 1\nLine 2\nLine 3") f.close() f = open("example.txt", "r") print(f.read()) f.close()Output:
Line 1 Line 2 Line 3Here, each
\nensures the text moves to a new line.
18. Besides whitespace, which characters are commonly used to separate values in text files?
A. Comma ( , ) and tab ( \t )
B. Dot ( . ) and semicolon ( ; )
C. Colon ( : ) and dash ( – )
D. Slash ( / ) and backslash ( \ )
Answer: A. Comma ( , ) and tab ( \t )
Explanation
Explanation:
- In text files, especially structured data files like CSV (Comma Separated Values) or TSV (Tab Separated Values), commas and tabs are commonly used as delimiters to separate individual values.
- This allows programs to parse and process the data correctly.
- Example:
CSV example:
Name,Age,City Mohan,18,Delhi Puja,15,MumbaiTSV example:
Name\tAge\tCity Mohan\t18\tDelhi Puja\t15\tMumbai
- In Python, the
csvmodule can handle both comma and tab separators.import csv with open("data.csv", "r") as f: reader = csv.reader(f) for row in reader: print(row)
19. How is a text file different from a .docx file?
A. A text file stores only ASCII data, whereas a .docx file includes formatting and metadata
B. A .docx file is smaller in size than a text file
C. Both store data only in binary symbols
D. A text file cannot be opened by Notepad
Answer: A. A text file stores only ASCII data, whereas a .docx file includes formatting and metadata
Explanation
Explanation:
- Text files (
.txt) store plain text in ASCII or Unicode. They do not include formatting (fonts, styles, colors) or metadata.- .docx files (Microsoft Word documents) are complex files that contain:
- Text content
- Formatting (bold, italics, font sizes)
- Page layout, images, tables
- Metadata (author, creation date, revision history)
- Hence,
.docxfiles are not directly readable in simple text editors like Notepad without losing formatting.Example:
Openingexample.txtin Notepad:Hello WorldOpening
example.docxin Notepad:PK�� ... (binary symbols representing formatting and XML content)
20. When comparing the file sizes of a .txt file and a .docx file containing the same text, what will you observe?
A. Both have the same size
B. The .txt file will be larger
C. The .docx file will be significantly larger
D. The .docx file will be smaller due to compression
Answer: C. The .docx file will be significantly larger
Explanation
Explanation:
- A
.txtfile stores only plain text, so it has minimal size — usually 1 byte per character.- A
.docxfile stores:
- Text content
- Formatting (bold, italics, fonts)
- Metadata (author, revision history)
- Page layout information
- Due to this extra data, a
.docxfile is significantly larger than a.txtfile containing the exact same text.Example:
example.txtcontaining “Hello World” → ~11 bytesexample.docxcontaining “Hello World” → ~10–15 KB (depends on Word version and metadata)
21. Which of the following statements about binary files is TRUE?
A. They store only ASCII characters
B. They contain human-readable text
C. They store data as bytes representing actual content like images or videos
D. They can be opened with any text editor
Answer: C. They store data as bytes representing actual content like images or videos
Explanation
Explanation:
- Binary files store data in raw byte format, not as human-readable characters.
- Examples include:
- Images:
.jpg,.png- Audio/Video:
.mp3,.mp4- Executables:
.exe,.bin- Unlike text files, binary files cannot be correctly read in a simple text editor because they include non-ASCII byte sequences representing the actual content.
Python Example:
# Writing binary data with open("example.bin", "wb") as f: f.write(b'\x89PNG\r\n\x1a\n') # First bytes of a PNG imageOpening
example.binin Notepad shows garbled symbols, not readable text.
22. What happens if we try to open a binary file using a text editor?
A. The file displays normally
B. The editor automatically converts it into text
C. It shows unreadable garbage characters
D. It will not open at all
Answer: C. It shows unreadable garbage characters
Explanation
Explanation:
- Text editors are designed to interpret bytes as ASCII/Unicode characters.
- Binary files contain machine-readable data (images, audio, videos, executables) that do not follow ASCII encoding.
- When a binary file is opened in a text editor, the editor tries to map bytes to characters, producing unreadable symbols or “garbage characters”.
Example:
Opening a PNG image in Notepad might display:‰PNG ��� IHDR���This is not meaningful text, it’s the raw byte data of the file.
23. A small change in a binary file, such as one bit flipped from 0 to 1, can cause:
A. No effect on file content
B. The file to become unreadable or corrupted
C. The file size to increase
D. The system to delete the file
Answer: B. The file to become unreadable or corrupted
Explanation
Explanation:
- Binary files store data in a precise sequence of bytes.
- Each bit represents part of the actual data (image pixels, audio samples, executable instructions, etc.).
- Even a single-bit change can alter the structure, making the file unreadable or corrupted by the program that uses it.
- Example:
- Flipping one bit in a PNG image may make it fail to open in an image viewer.
- Changing a byte in an executable could make it fail to run.
This is why binary files are more sensitive to corruption than text files.
24. Why is it difficult to correct errors in binary files manually?
A. Because they use a compressed format
B. Because the data is not stored sequentially
C. Because the content is not human-readable
D. Because Python doesn’t support binary editing
Answer: C. Because the content is not human-readable
Explanation
Explanation:
- Binary files store data as raw bytes representing images, audio, videos, or executable instructions.
- Unlike text files, this data is not human-readable, meaning we cannot easily see the content or understand its structure.
- Therefore, manual correction of errors in binary files is extremely difficult. Specialized software tools (like hex editors) are required to modify or repair binary data.
Example:
Opening a.pngor.exefile in Notepad shows garbled symbols, making it impossible to fix an error just by reading the content.
25. Which module in Python provides functions to handle files such as reading and writing?
A. sys
B. os
C. io
D. file
Answer: C. io
Explanation
Explanation:
- Python uses the
iomodule to handle all file input/output operations.- The module provides classes and methods for both text and binary files:
- Text files:
io.TextIOWrapper- Binary files:
io.BufferedReader,io.BufferedWriter- In-memory streams:
io.StringIO,io.BytesIO- Even though the built-in
open()function is commonly used, it internally relies on theiomodule.Example:
import io # Writing to a text file with io.open("example.txt", "w", encoding="utf-8") as f: f.write("Hello Puja\n") # Reading from a text file with io.open("example.txt", "r", encoding="utf-8") as f: print(f.read())
26. What is the primary purpose of the open() function in Python?
A. To import the io module
B. To connect a Python program with a data file
C. To print data from the file
D. To rename a file
Answer: B. To connect a Python program with a data file
Explanation
Explanation:
- The
open()function in Python is used to open a file and create a file object that acts as a link between the program and the actual file stored on secondary storage (HDD, SSD).- Once a file is opened, we can perform read, write, or append operations using the file object.
- Syntax:
file_object = open("filename.txt", "mode")Common modes:
'r'→ read'w'→ write (overwrites existing content)'a'→ append'rb'/'wb'→ binary read/writeExample:
# Open a file in write mode f = open("example.txt", "w") f.write("Hello Puja\n") f.close()Here,
open()establishes the connection between Python and the file for operations.
27. The correct syntax of the open() function is:
A. file = open(filename)
B. file = open(filename, access_mode)
C. open.file(filename, mode)
D. open(filename, mode, variable)
Answer: B. file = open(filename, access_mode)
Explanation
Explanation:
- The correct syntax of the
open()function in Python is:file_object = open(filename, access_mode)
- Parameters:
filename→ Name of the file (string)access_mode→ Mode in which the file is opened ('r','w','a','rb','wb', etc.)- The function returns a file object (handle), which can be used to read from or write to the file.
Example:
# Open a file in read mode f = open("example.txt", "r") content = f.read() f.close() print(content)Here,
fis the file object returned byopen().
- Other options are incorrect:
open.file()→ invalid syntaxopen(filename, mode, variable)→ no third argument calledvariable
28. What does the open() function return after successfully opening a file?
A. A Boolean value
B. A string containing file path
C. A file object (file handle)
D. The number of bytes in the file
Answer: C. A file object (file handle)
Explanation
Explanation:
- When a file is successfully opened using
open(), Python returns a file object, also called a file handle.- This object acts as an interface to perform operations like reading, writing, or appending data to the file.
- Example:
# Opening a file in write mode f = open("example.txt", "w") # f is the file object f.write("Hello Puja\n") f.close()
- The file object provides methods like:
.read(),.readline(),.readlines()→ reading data.write(),.writelines()→ writing data.close()→ closing the file- Other options are incorrect:
- Boolean → only returned if an error check is performed
- String containing file path → no, file object is returned
- Number of bytes → not returned by
open()
29. If the file mentioned in the open() function does not exist, what happens?
A. The program stops with an error (if mode is 'r')
B. A new empty file is automatically created (if mode is 'w', 'a', or 'x')
C. The system shuts down
D. Python ignores the command
Answer: B. A new empty file is automatically created
Explanation
Explanation:
- Behavior depends on the mode specified:
'r'→ Raises FileNotFoundError if the file does not exist.'w'→ Creates a new empty file if it does not exist.'a'→ Creates a new empty file if it does not exist, then appends data.'x'→ Creates a new file, but raises an error if it already exists.Example in Python:
# Writing mode creates a new file if it doesn't exist f = open("newfile.txt", "w") f.write("Hello Mohan\n") f.close() # Reading mode raises error if file doesn't exist f = open("nofile.txt", "r") # FileNotFoundError
- Key Point: Python does not always create a file automatically. Automatic creation happens only in write (
w), append (a), or exclusive-create (x) modes.
30. The attribute <file.closed> in Python is used to:
A. Display file contents
B. Return True if the file is closed, else False
C. Delete a file from memory
D. Check file permissions
Answer: B. Return True if the file is closed, else False
Explanation
Explanation:
- In Python, every file object has a
closedattribute.- This attribute indicates whether the file is currently closed:
True→ file is closedFalse→ file is still openExample:
f = open("example.txt", "w") print(f.closed) # Output: False f.write("Hello Mohan\n") f.close() print(f.closed) # Output: True
- Using
file.closedis useful to check file state before performing operations, helping avoid errors like writing to a closed file.
31. Binary files are stored in terms of:
A. Characters
B. ASCII values
C. Bytes
D. Unicode
Answer: C. Bytes
Explanation
Explanation:
- Binary files store data in raw byte format (0s and 1s).
- These bytes can represent anything — images, audio, videos, executables, etc.
- Unlike text files, binary files are not directly human-readable.
- Programs interpret these bytes according to the file type to display or process the content.
Example:
# Writing binary data data = bytes([120, 3, 255, 0, 100]) with open("binaryfile.bin", "wb") as f: f.write(data) # Reading binary data with open("binaryfile.bin", "rb") as f: content = f.read() print(content) # Output: b'x\x03\xff\x00d'
- Here,
b'x\x03\xff\x00d'is the byte representation of the data.
32. What happens if you try to open a binary file using a text editor?
A. The file opens normally
B. The text editor automatically converts it
C. The file displays garbage values
D. The file gets deleted
Answer: C. The file displays garbage values
Explanation
Explanation:
- Binary files store data in raw bytes, not in human-readable text.
- A text editor interprets these bytes as ASCII or Unicode characters.
- Since many bytes do not correspond to valid characters, the editor shows random symbols, unreadable characters, or garbage.
- To correctly view or manipulate binary files, specialized programs or binary editors are required.
Example:
# Writing binary data data = bytes([72, 101, 108, 108, 111, 255]) with open("binaryfile.bin", "wb") as f: f.write(data)
- Opening
binaryfile.binin Notepad will show garbled symbols because255does not map to a readable ASCII character.
33. Which module in Python is used for handling files?
A. os
B. sys
C. io
D. file
Answer: C. io
Explanation
Explanation:
- Python’s
iomodule provides classes and functions for file input/output operations.- It supports both text and binary files, allowing consistent handling of:
- Reading:
.read(),.readline(),.readlines()- Writing:
.write(),.writelines()- In-memory streams:
io.StringIO,io.BytesIO- While the built-in
open()function is commonly used, it internally uses theiomodule.Example:
import io # Writing text using io module with io.open("example.txt", "w", encoding="utf-8") as f: f.write("Hello Mohan\n") # Reading text using io module with io.open("example.txt", "r", encoding="utf-8") as f: print(f.read())
- Other options:
os→ Operating system interface (like file deletion or renaming)sys→ System-specific parametersfile→ No such module in Python
34. What does the function open(filename, mode) return in Python?
A. File name only
B. File handle or file object
C. File size
D. File extension
Answer: B. File handle or file object
Explanation
Explanation:
- The
open()function in Python opens a file and returns a file object (also called a file handle).- This file object acts as an interface between your program and the file stored on disk.
- Using the file object, you can perform operations like:
- Reading:
.read(),.readline(),.readlines()- Writing:
.write(),.writelines()- Closing:
.close()Example:
# Open a file in write mode f = open("example.txt", "w") # f is the file object f.write("Hello Mohan\n") f.close()
- Here,
fis the file object, which you use to write data to the file.- Other options are incorrect:
- File name → not returned
- File size → not returned
- File extension → not returned
35. What does file.closed return?
A. File name
B. File path
C. True if file is closed, else False
D. File size
Answer: C. True if file is closed, else False
Explanation
Explanation:
- In Python, every file object has a
closedattribute.- It indicates whether the file is currently closed:
True→ the file has been closedFalse→ the file is still openExample:
f = open("example.txt", "w") print(f.closed) # Output: False f.write("Hello Mohan\n") f.close() print(f.closed) # Output: True
- Checking
file.closedis useful to avoid operations on closed files, which would otherwise raise errors.
36. What does file.mode return?
A. File’s data type
B. Access mode used while opening the file
C. File name
D. File offset position
Answer: B. Access mode used while opening the file
Explanation
Explanation:
- In Python, every file object has a
modeattribute.- This attribute tells you how the file was opened:
'r'→ read mode'w'→ write mode'a'→ append mode'rb','wb','ab'→ binary modes'w+','r+','a+'→ read/write combinationsExample:
f = open("example.txt", "w") print(f.mode) # Output: w f.close() f = open("example.txt", "rb") print(f.mode) # Output: rb f.close()
- This helps in verifying or debugging the file’s access mode before performing operations.
- Other options are incorrect:
- File’s data type → not related
- File name → use
file.nameinstead- File offset → use
file.tell()
37. Which of the following opens a file in read-only mode?
A. 'r'
B. 'w'
C. 'a'
D. 'r+'
Answer: A. 'r'
Explanation
Explanation:
- The
'r'mode in Python opens a file for reading only.- The file must exist, otherwise Python raises FileNotFoundError.
- Reading starts from the beginning of the file.
- You cannot write to a file opened in
'r'mode.Other modes for comparison:
'w'→ write mode (creates file if it doesn’t exist, overwrites if it exists)'a'→ append mode (creates file if it doesn’t exist, writes at end)'r+'→ read/write mode (file must exist, allows both reading and writing)Example:
f = open("example.txt", "r") content = f.read() print(content) f.close()
38. Which of these modes opens a file for writing in binary mode, overwriting its contents?
A. 'wb'
B. 'rb'
C. 'ab'
D. 'r+'
Answer: A. 'wb'
Explanation
Explanation:
'wb'mode stands for write-binary.- Behavior:
- If the file exists, its contents are erased before writing.
- If the file does not exist, a new file is created.
- Binary mode ensures that data is written in raw bytes, not text.
Other modes for comparison:
'rb'→ read-binary mode, file must exist'ab'→ append-binary mode, data is added to end without overwriting'r+'→ read/write mode (text by default), file must existExample:
# Writing binary data data = bytes([10, 20, 30]) with open("binaryfile.bin", "wb") as f: f.write(data)
- This will overwrite the file if it already exists.
39. If you open a file using mode 'ab+', what happens?
A. File opens at the beginning for reading and writing
B. File opens at the end for appending and reading
C. File content gets deleted
D. File is opened only for reading
Answer: B. File opens at the end for appending and reading
Explanation
Explanation:
'ab+'mode stands for append-binary plus:
- Opens the file in binary mode.
- Allows reading (
+) and appending (a).- Behavior:
- Data is appended at the end of the file.
- Existing content is preserved; nothing is overwritten.
- If the file does not exist, a new file is created.
Example:
# Appending binary data and reading with open("binaryfile.bin", "ab+") as f: f.write(bytes([100, 101])) f.seek(0) # Move to beginning for reading content = f.read() print(content)
- Here, new data is added at the end, but you can still read the full file using
.seek(0).
40. In which mode does the file pointer start at the end of the file?
A. 'r'
B. 'a'
C. 'w'
D. 'rb'
Answer: B. 'a'
Explanation
Explanation:
'a'mode stands for append:
- Opens the file for writing only.
- The file pointer is positioned at the end, so any new data is appended after existing content.
- If the file does not exist, a new file is created.
- Other modes for comparison:
'r'→ file pointer at beginning, read-only'w'→ file is truncated, pointer at beginning'rb'→ read-binary mode, pointer at beginningExample:
with open("example.txt", "a") as f: f.write("Hello Mohan\n") # Added at end of file
- Existing data in the file remains intact; new content is appended.
41. Which access mode creates a new file if it does not exist and overwrites if it does?
A. 'r'
B. 'a'
C. 'w'
D. 'rb'
Answer: C. 'w'
Explanation
Explanation:
'w'mode stands for write:
- Creates a new file if it does not exist.
- Overwrites existing content if the file already exists.
- Behavior:
- Data written using
'w'replaces any previous data in the file.- Other modes for comparison:
'r'→ read-only, file must exist'a'→ append, preserves existing data'rb'→ read-binary, file must existExample:
with open("example.txt", "w") as f: f.write("Hello Mohan\n") # Overwrites existing content
- If
example.txtexisted, its previous content is erased.
42. What is the default mode of open() function if not specified?
A. 'r'
B. 'w'
C. 'a'
D. 'rb'
Answer: A. 'r'
Explanation
Explanation:
- If you call
open(filename)without specifying a mode, Python uses'r'by default.- ‘r’ mode:
- Opens the file in read-only mode.
- File must exist, otherwise FileNotFoundError is raised.
- File pointer starts at the beginning of the file.
Example:
f = open("example.txt") # Default mode is 'r' content = f.read() print(content) f.close()
- Other modes like
'w','a','rb'must be explicitly specified.
43. What does the following code do?
f = open("data.bin", "rb+")
A. Opens file for read only
B. Opens file for binary read and write
C. Opens file for append
D. Creates file if not exist
Answer: B. Opens file for binary read and write
Explanation
Explanation:
'rb+'mode stands for read and write in binary:
- Opens an existing binary file for both reading and writing.
- File pointer starts at the beginning of the file.
- File must exist, otherwise FileNotFoundError is raised.
- Other modes for comparison:
'r'→ read-only (text mode)'w'→ write-only, overwrites file'a'→ append mode'wb+'→ write-binary plus (creates new file if not exist)Example:
with open("data.bin", "rb+") as f: content = f.read() print(content) f.seek(0) f.write(bytes([100, 101]))
- Reads the file first, then writes binary data at the beginning.
44. Which mode allows reading and writing in binary, overwriting existing content?
A. 'rb+'
B. 'wb+'
C. 'ab+'
D. 'r+'
Answer: B. 'wb+'
Explanation
Explanation:
'wb+'mode stands for write-binary plus:
- Opens the file in binary mode.
- Allows both reading and writing.
- If the file exists, its content is erased.
- If the file does not exist, a new file is created.
- Other modes for comparison:
'rb+'→ read/write binary, does not overwrite, file must exist'ab+'→ append/write binary, adds data at end, preserves existing content'r+'→ read/write text, does not create new fileExample:
with open("binaryfile.bin", "wb+") as f: f.write(bytes([10, 20, 30])) # Overwrites any existing content f.seek(0) print(f.read()) # Reads the new content
- This mode is useful when you want a fresh binary file but also need to read it immediately.
45. Which attribute returns the name of the file opened using open() function?
A. file.name
B. file.title
C. file.path
D. file.mode
Answer: A. file.name
Explanation
Explanation:
- In Python, every file object has a
nameattribute.file.namegives the name of the file, including the path if provided.- Useful for debugging or logging file operations.
Example:
f = open("example.txt", "w") print(f.name) # Output: example.txt f.close()
- Other attributes:
file.mode→ mode in which the file was openedfile.closed→ indicates whether the file is closedfile.title/file.path→ do not exist in Python file objects
46. Which method in Python is used to close a file after read/write operations?
A. end()
B. stop()
C. close()
D. terminate()
Answer: C. close()
Explanation
Explanation:
close()method is used to close an open file.- Closing a file ensures:
- All data is flushed from memory to the file.
- System resources are released.
- Further operations on the file raise an error if attempted.
Example:
f = open("example.txt", "w") f.write("Hello Mohan\n") f.close() print(f.closed) # Output: True
- Best practice: Always close a file after operations.
- Alternative: Use
withstatement to automatically close:with open("example.txt", "w") as f: f.write("Hello Mohan\n") # File automatically closed here
47. What happens when a file is closed using close() method?
A. File gets deleted
B. File becomes inaccessible until reopened
C. File content is erased
D. The program terminates
Answer: B. File becomes inaccessible until reopened
Explanation
Explanation:
- Calling
file.close()terminates the connection between the program and the file.- Consequences:
- File cannot be read from or written to until it is reopened.
- Any buffered data is flushed to the file.
- System resources associated with the file are released.
- The file itself is not deleted or erased; the data remains intact.
Example:
f = open("example.txt", "w") f.write("Hello Mohan\n") f.close() # Further operations will raise ValueError # f.write("More text") # ValueError: I/O operation on closed file
- Best practice: Always close files to avoid resource leaks.
- Alternatively, using
withstatement automatically closes the file:with open("example.txt", "w") as f: f.write("Hello Mohan\n") # File is closed automatically here
48. What is the main advantage of closing a file after use?
A. Prevents file renaming
B. Saves memory and writes unsaved data
C. Automatically changes file mode
D. Encrypts the file content
Answer: B. Saves memory and writes unsaved data
Explanation
Explanation:
- Closing a file using
close()ensures that:
- Any unsaved or buffered data is written (flushed) to the disk.
- Memory resources associated with the file are released.
- Not closing a file can lead to:
- Data loss if buffered data isn’t written.
- Resource leaks, which may affect program performance.
- Best practice: Use
withstatement to automatically handle closing:with open("example.txt", "w") as f: f.write("Hello Mohan\n") # File is automatically closed here
- This ensures safe and efficient file handling.
49. What will happen if a file object is reassigned to another file before closing the previous one?
A. Python throws an error
B. Both files remain open
C. The previous file is automatically closed
D. The previous file’s data is lost
Answer: B. Both files remain open
Explanation
Explanation:
- In Python, file objects are managed by references.
- Reassigning a variable pointing to a file object (e.g.,
f = open("file2.txt")) does not automatically close the previous file (file1.txt).- If the previous file isn’t closed using
f.close(), it remains open and may lead to:
- Data not flushed properly
- Resource leaks
- Best practice: Always close files explicitly or use the
withstatement:# Incorrect way (can leave file open) f = open("file1.txt", "w") f = open("file2.txt", "w") # file1.txt is still open! # Correct way f = open("file1.txt", "w") f.write("Hello Mohan\n") f.close() f = open("file2.txt", "w") f.write("Another file\n") f.close() # Or use 'with' to auto-close with open("file1.txt", "w") as f: f.write("Hello Mohan\n")Key Point: Python garbage collector may eventually close the file, but relying on this is unsafe.
50. What is the purpose of the with clause in file handling?
A. To open multiple files simultaneously
B. To automatically close the file after its block execution
C. To delay writing operations
D. To rename the file after writing
Answer: B. To automatically close the file after its block execution
Explanation
Explanation:
- The
withstatement is a context manager in Python.- Benefits of using
withfor file handling:
- Automatically calls
file.close()at the end of the block.- Ensures resources are released, even if exceptions occur.
- Makes code cleaner and safer than manually opening and closing files.
Example:
with open("example.txt", "w") as f: f.write("Hello Mohan\n") # File is automatically closed here
- Without
with, you’d have to manually callf.close().
51. Choose the correct syntax of opening a file using the with clause.
A. with open(file_name, mode):
B. open with(file_name, mode):
C. with file_name.open(mode):
D. file open with(mode):
Answer: A. with open(file_name, mode):
Explanation
Explanation:
- The
withstatement is used as a context manager to handle files safely.- Correct syntax:
with open("example.txt", "r") as f: content = f.read() # File is automatically closed after this block
- Key Points:
open(file_name, mode)→ opens the file with the specified mode ('r','w','a', etc.).as file_object→ assigns the file object to a variable for operations inside the block.- Automatic closure occurs even if an error is raised inside the block.
- This syntax eliminates the need to manually call
close().
52. Which of the following statements is true regarding the with clause?
A. The file must be closed manually
B. It closes the file automatically after the block is executed
C. It keeps the file open permanently
D. It can only be used with binary files
Answer: B. It closes the file automatically after the block is executed
Explanation
Explanation:
- The
withstatement in Python acts as a context manager.- Benefits:
- Automatic closure: The file is closed automatically after the indented block is executed.
- Error safety: Even if an exception occurs inside the block, the file is closed safely.
- Cleaner code: No need to explicitly call
file.close().- Usage: Can be used for both text and binary files.
Example:
with open("example.txt", "r") as f: content = f.read() # File is automatically closed here
- This ensures efficient resource management and prevents file corruption.
53. In the statement
with open("myfile.txt", "r+") as myObject:
content = myObject.read()
What is the mode used here?
A. Append mode
B. Read-only mode
C. Read and Write mode
D. Write-only mode
Answer: C. Read and Write mode
Explanation
Explanation:
- The
"r+"mode in Python:
- Opens the file for both reading and writing.
- File must exist; otherwise, it raises
FileNotFoundError.- Reading/writing starts from the beginning of the file.
- Difference from other modes:
'r'→ read-only'w'→ write-only (overwrites existing content)'a'→ append (write at end)'r+'→ read/write (does not overwrite automatically)Example:
with open("myfile.txt", "r+") as f: print(f.read()) # Read existing content f.write("\nHello Mohan") # Append data starting at current pointer
- This mode is useful when you need to read and modify a file without erasing existing content.
54. What happens if a file is opened in write mode (‘w’) and the file already exists?
A. The file is appended
B. An error occurs
C. File is deleted permanently
D. Its contents are erased before writing new data
Answer: D. Its contents are erased before writing new data
Explanation
Explanation:
- The
'w'mode in Python:
- Opens a file for writing only.
- If the file exists, its entire content is erased.
- If the file does not exist, a new empty file is created.
- Use case: Suitable when you want to replace old content with new data.
Example:
# Existing file example.txt has "Old content" f = open("example.txt", "w") f.write("Hello Mohan\n") # Overwrites old content f.close()
- After execution, the file contains only
"Hello Mohan\n"; old content is lost.
55. When a file is opened in append mode (‘a’), where is the file pointer positioned?
A. Beginning of file
B. Middle of file
C. End of file
D. Random position
Answer: C. End of file
Explanation
Explanation:
- In append mode
'a':
- The file pointer is automatically positioned at the end of the file.
- New data is added after existing content.
- Existing content is never overwritten.
- Behavior if file doesn’t exist:
- Python creates a new empty file.
Example:
with open("example.txt", "a") as f: f.write("Hello Mohan\n") # Added at the end of existing file content
- Append mode is ideal for log files or data collection files where preserving existing content is important.
56. Which of the following modes allows both reading and appending in a file?
A. 'w+'
B. 'a+'
C. 'r+'
D. 'rb'
Answer: B. 'a+'
Explanation
Explanation:
'a+'mode in Python:
- Opens the file for both reading and appending.
- The file pointer is positioned at the end of the file for writing.
- Existing content is not overwritten.
- You can read the file, but new data is always added at the end.
- Difference from
'r+':
'r+'allows reading and writing starting from the beginning, overwriting data if written.'a+'preserves existing content and writes only at the end.Example:
with open("example.txt", "a+") as f: f.write("New line added\n") # Appended at the end f.seek(0) # Move pointer to start to read print(f.read()) # Reads the entire file content
57. Which of the following statements about with clause is incorrect?
A. It automatically closes the file
B. It requires manual closing
C. It prevents memory leakage
D. It simplifies code readability
Answer: B. It requires manual closing
Explanation
Explanation:
- The
withstatement in Python is a context manager.- Key points:
- Automatically calls
file.close()at the end of the block.- Prevents memory/resource leaks by ensuring the file is properly closed.
- Improves code readability and reduces errors.
- Statement B is incorrect because manual closing is not needed when using
with.Example:
with open("example.txt", "r") as f: data = f.read() # File is automatically closed here
- No
f.close()is required; Python handles it internally.
58. The following code:
myObject = open("data.txt", "a+")opens the file for:
A. Reading only
B. Writing only
C. Reading and appending
D. Writing and truncating
Answer: C. Reading and appending
Explanation
Explanation:
'a+'mode in Python:
- Opens the file for reading and appending.
- The file pointer is positioned at the end of the file for writing.
- Existing content is preserved; new data is added after existing data.
- Reading is allowed after moving the pointer using
seek().Example:
f = open("data.txt", "a+") f.write("Hello Mohan\n") # Appended at the end f.seek(0) # Move pointer to start for reading print(f.read()) # Reads entire file f.close()
- Ideal for log files or data collection where existing content must not be lost.
59. Why is the with statement preferred over using open() and close() separately?
A. It consumes more memory
B. It reduces syntax errors and ensures safe closure
C. It only works in Python 3.10+
D. It writes faster
Answer: B. It reduces syntax errors and ensures safe closure
Explanation
Explanation:
- The
withstatement is a context manager in Python.- Advantages over separate
open()andclose()calls:
- Automatic resource management: Ensures the file is closed automatically even if exceptions occur.
- Reduces syntax errors: No need to remember
file.close()manually.- Cleaner and more readable code: Indentation clearly shows the scope of file operations.
- Example:
with open("example.txt", "r") as f: data = f.read() # File is automatically closed here
- Using
open()andclose()separately could lead to resource leaks ifclose()is forgotten or an error occurs before it is called.
60. What will happen if an exception occurs inside a with block?
A. File remains open
B. File closes automatically
C. File gets deleted
D. File becomes read-only
Answer: B. File closes automatically
Explanation
Explanation:
- The
withstatement in Python acts as a context manager.- Behavior during exceptions:
- When an exception occurs inside the
withblock, Python ensures the file is properly closed before propagating the exception.- This prevents resource leaks and keeps file handling safe.
- Example:
try: with open("example.txt", "r") as f: data = f.read() raise Exception("Something went wrong") except Exception as e: print(e) # File is automatically closed despite the exception
- Even though an exception is raised,
example.txtis closed safely, ensuring proper resource management.
61. Which method in Python is used to write a single string into a text file?
A. write()
B. writelines()
C. read()
D. append()
Answer: A. write()
Explanation
Explanation:
- The
write()method writes a single string to a file.- Key points:
- Takes a string as an argument and writes it to the file.
- Returns the number of characters written.
- Does not automatically add a newline; you must include
\nexplicitly if needed.- Difference from
writelines():
writelines()writes a list of strings to the file, without adding newlines automatically.Example:
with open("example.txt", "w") as f: chars_written = f.write("Hello Mohan\n") print(chars_written) # Output: 12 (number of characters written)
- Here,
"Hello Mohan\n"is written as a single string into the file.
62. The write() method returns:
A. Nothing
B. Boolean value
C. The number of characters written
D. The file name
Answer: C. The number of characters written
Explanation
Explanation:
- When using
file.write(string):
- It writes the string to the file.
- Returns an integer representing the number of characters successfully written.
- Includes all characters, including newline characters (
\n) if present.- Example:
with open("example.txt", "w") as f: chars_written = f.write("Hello Mohan\n") print(chars_written) # Output: 12
- Useful to verify how many characters were written to the file.
63. What is the output of the following code?
myfile = open("demo.txt", "w")
x = myfile.write("Python\nFile Handling")
print(x)
myfile.close()
A. 0
B. 19
C. 20
D. 21
Answer: C. 20
Explanation
Explanation:
Concept Behind the Code
- open(“demo.txt”, “w”)
- Opens a text file named
demo.txtin write mode ("w").- If the file already exists, its old content is erased.
- If it doesn’t exist, a new file is created.
- write(“Python\nFile Handling”)
- Writes the given string to the file.
- Returns an integer — the number of characters successfully written.
\nis a single newline character, not two separate characters.- print(x)
- Prints the return value of the
write()method, i.e., the number of characters written to the file.- myfile.close()
- Closes the file and ensures all data is properly saved.
Counting the Characters
Let’s count the number of characters in
"Python\nFile Handling":
Character Count P 1 y 2 t 3 h 4 o 5 n 6 \n (newline) 7 F 8 i 9 l 10 e 11 (space) 12 H 13 a 14 n 15 d 16 l 17 i 18 n 19 g 20 Total characters = 20
Important Note
\nis counted as a single character (newline), not as two separate symbols (\andn).
Hence, the total number of characters in the string is 20.You can verify this using:
len("Python\nFile Handling") # Output: 20Final Output
20
64. In the statement myfile.write("Hello\nWorld"), the \n represents:
A. Null value
B. Tab space
C. End of line
D. End of file
Answer: C. End of line (newline)
Explanation
Explanation:
- In Python strings,
\nis known as the newline character.- It instructs the program to move the cursor to the next line, thereby marking the end of the current line.
- When the string
"Hello\nWorld"is written to a file, it appears as:Hello WorldHere,
\ncreates a line break between “Hello” and “World”.Key Points
\n→ newline (end of line)\t→ tab space\0→ null character (in C, not typically used in Python)EOF→ end of file (not represented by\n)Example
with open("example.txt", "w") as f: f.write("Hello\nWorld")Content inside the file:
Hello World
65. What will happen if you use the write() method to write numeric data directly?
A. It will be written as integer
B. It will raise a TypeError
C. It will convert automatically
D. It will write ASCII value
Answer: B. It will raise a TypeError
Explanation
Explanation:
- The
write()method in Python accepts only string-type data as input.- If you try to write numeric data (like an integer or float) directly using
write(), Python will raise a TypeError, because integers cannot be written to a file without conversion.Example
with open("data.txt", "w") as f: f.write(123) # This will cause an errorOutput:
TypeError: write() argument must be str, not intCorrect Way
To write numeric data, you must convert it to a string using the
str()function:with open("data.txt", "w") as f: f.write(str(123)) # Works correctlyFile content:
123Key Point
write()→ accepts only string type.- For numbers or other data types, use type conversion (
str()) before writing.- For structured data, Python provides pickle or JSON modules.
66. Which of the following statements correctly writes a numeric value into a file?
A. myfile.write(123)
B. myfile.write(str(123))
C. myfile.writelines(123)
D. myfile.write(int(123))
Answer: B. myfile.write(str(123))
Explanation
Explanation:
- The
write()method in Python only accepts string-type data.- If you try to pass an integer directly (as in
myfile.write(123)), Python will raise a TypeError, because the method expects a string.- To write numeric data successfully, you must convert the number to a string using the
str()function.Example
myfile = open("demo.txt", "w") myfile.write(str(123)) # Correct way myfile.close()Content of demo.txt:
123If you try:
myfile.write(123) # IncorrectPython will show:
TypeError: write() argument must be str, not intKey Points
write()→ accepts only string input.- To write numbers → convert using
str().writelines()also requires a sequence of strings, not integers.- Functions like
pickle.dump()orjson.dump()can write non-string objects, but in text files, conversion is necessary.
67. The flush() method in Python is used to:
A. Erase file data
B. Close the file automatically
C. Write buffer contents to the file immediately
D. Move file pointer to start
Answer: C. Write buffer contents to the file immediately
Explanation
Explanation:
- In Python, file operations are buffered.
- When data is written using
write(), it is first stored in an in-memory buffer.- It may not be immediately written to the physical file on disk.
- The
flush()method forces the buffer to write its content to the file immediately, without closing the file.- This is useful when you want to ensure that all written data is physically saved to the file while the program is still running.
Example
with open("demo.txt", "w") as f: f.write("Hello World") f.flush() # Forces the buffer to write "Hello World" to demo.txt immediately # File is still open hereExplanation:
- Without
flush(), data may remain in memory temporarily until the file is closed or the buffer is full.flush()ensures data integrity especially in long-running programs or logging scenarios.Key Points
flush()does not close the file.- It does not erase data.
- The file pointer remains unchanged; only the buffer is cleared by writing its content.
68. Which of the following correctly writes multiple strings to a file in one go?
A. write(["A","B","C"])
B. writelines(["A","B","C"])
C. write("A","B","C")
D. write(list("ABC"))
Answer: B. writelines(["A","B","C"])
Explanation
Explanation:
- The
writelines()method in Python is used to write multiple strings to a file sequentially.- It accepts an iterable (like a list, tuple, or generator) containing string elements.
- Unlike
write(),writelines()does not add newline characters automatically. If you want each string on a new line, you must include\nexplicitly in the strings.Example
lines = ["Hello\n", "World\n", "Python\n"] with open("demo.txt", "w") as f: f.writelines(lines)Content of
demo.txt:Hello World PythonExplanation:
- Each element of the list is written in sequence.
- No extra characters or separators are added automatically.
Key Points
write()→ writes a single string.writelines()→ writes multiple strings from an iterable.- To write each string on a new line, include
\nin each element of the iterable.
69. What is the difference between write() and writelines()?
A. write() writes multiple lines; writelines() only one
B. write() accepts string; writelines() accepts iterable of strings
C. Both are identical
D. write() is faster
Answer: B. write() accepts string; writelines() accepts iterable of strings
Explanation
Explanation:
write():
- Writes a single string to a file.
- Returns the number of characters written.
- Example:
with open("demo.txt", "w") as f: f.write("Hello World\n")writelines():
- Writes multiple strings passed as an iterable (like a list, tuple, or generator).
- Does not add newline characters automatically, so
\nmust be included if needed.- Example:
lines = ["Hello\n", "World\n", "Python\n"] with open("demo.txt", "w") as f: f.writelines(lines)Key Points
Method Accepts Writes Newline Added Automatically? write()Single string One string No writelines()Iterable of strings All strings in the iterable No
write()→ ideal for single string writing.writelines()→ ideal for writing multiple lines at once.
70. If we open a file in write mode (‘w’) and call write() twice, what will happen?
A. Only the first write is saved
B. Only the last write is saved
C. Both will be written sequentially
D. File will raise an error
Answer: C. Both will be written sequentially
Explanation
Explanation:
- When a file is opened in write mode (
'w'), Python prepares the file to overwrite existing content.- Each call to
write()writes the provided string sequentially to the file at the current file pointer location.- The file pointer moves forward after each write, so multiple calls to
write()will append data in sequence within the same open session.- The content will remain in the file after it is closed.
Example
with open("demo.txt", "w") as f: f.write("Hello\n") f.write("World\n")Content of
demo.txt:Hello WorldExplanation:
- The first
write()writes"Hello\n".- The second
write()writes"World\n"immediately after the first string.- Both strings are preserved sequentially in the file.
Key Points
- Write mode (
'w') erases previous content at the start, but subsequent writes in the same session are appended sequentially.- To overwrite content, the file must be reopened in
'w'mode again.write()does not automatically add a newline; it must be included if needed (\n).
71. What is the correct statement about buffer in Python file handling?
A. Buffer stores data temporarily before writing to disk
B. Buffer prevents data loss
C. Data is written directly to the disk
D. Buffer is not used in file handling
Answer: A. Buffer stores data temporarily before writing to disk
Explanation
Explanation:
- In Python, file operations are buffered for efficiency.
- When
write()is called, the data is first stored in a memory buffer instead of being written directly to the disk.- The buffer improves performance by reducing the number of disk writes.
- Data in the buffer is written to the physical file when:
- The file is closed using
close().flush()is explicitly called to force writing immediately.- The buffer is full (depending on the system and Python implementation).
Example
with open("demo.txt", "w") as f: f.write("Hello World") # Data goes to buffer first f.flush() # Buffer is written to disk immediately
- Without
flush(), data would still be written to disk automatically whenfis closed.Key Points
- Buffering improves efficiency by reducing frequent disk writes.
flush()can be used to manually write the buffer contents to disk.- Closing the file also automatically flushes the buffer.
“BufferedWriter writes data to a buffer, which is then written to the underlying raw stream, improving efficiency.”
72. In which situation is it necessary to use flush() manually?
A. When working with large files that must update frequently
B. When file is read-only
C. When using with statement
D. When file is already closed
Answer: A. When working with large files that must update frequently
Explanation
Explanation:
- In Python, file operations are buffered for efficiency.
- Data written using
write()is first stored in a memory buffer and may not immediately appear in the physical file.- Using
flush()forces the buffer to write its contents to disk immediately, ensuring that even partially written data is saved.- This is particularly important in situations such as:
- Logging large files in real-time.
- Data streaming or monitoring applications where updates must be visible immediately.
- Without
flush(), the data may remain in memory until the buffer fills up or the file is closed.Example
with open("log.txt", "w") as f: for i in range(1000): f.write(f"Line {i}\n") f.flush() # Ensures each line is immediately written to diskExplanation:
- Each line is written and flushed immediately.
- This ensures that even if the program crashes, the most recent lines are saved.
Key Points
flush()is not needed if the file is closed normally, asclose()automatically flushes the buffer.- It is required when data must be visible immediately on disk before closing.
“Flush the write buffer of the stream if applicable. This ensures that data is written to the underlying raw stream immediately.”
73. What does the following code do?
data = ["Line1\n", "Line2\n", "Line3\n"]
myfile = open("info.txt", "w")
myfile.writelines(data)
myfile.close()A. Writes only the first string
B. Writes all three strings to info.txt
C. Produces a TypeError
D. Writes nothing
Answer: B. Writes all three strings to info.txt
Explanation
Explanation:
- The
writelines()method writes all elements of an iterable (like a list or tuple) sequentially to the file.- Each string in the iterable is written exactly as it is.
- Since the strings in
datainclude\n, each line will appear on a new line in the file.Example
Content of
info.txtafter execution:Line1 Line2 Line3
- The first element
"Line1\n"is written.- Then
"Line2\n"and"Line3\n"are written sequentially.- No TypeError occurs because
writelines()accepts an iterable of strings.Key Points
writelines()does not automatically add newlines. If newlines are needed, they must be included in the strings (as done here with\n).write()writes one string at a time, whereaswritelines()writes multiple strings from an iterable.“writelines(lines) writes each element of the given iterable to the stream in order.”
74. Which statement about writelines() is incorrect?
A. It does not add newline automatically
B. It writes multiple strings from an iterable
C. It adds \n after each element automatically
D. Each string must already contain newline if desired
Answer: C. It adds \n after each element automatically
Explanation
Explanation:
- The
writelines()method writes all elements of an iterable (like a list or tuple) sequentially to a file.- Important points about
writelines():
- It does not add newline characters automatically.
- Each string in the iterable is written exactly as provided.
- If a newline is desired, it must be included in the string itself, e.g.,
"Line1\n".Example
lines = ["Hello\n", "World\n", "Python"] with open("demo.txt", "w") as f: f.writelines(lines)Content of
demo.txt:Hello World PythonExplanation:
"Hello\n"→ newline included"World\n"→ newline included"Python"→ no newline, so it stays on the same line if appended
writelines()does not automatically insert\nbetween elements.- This is a common misconception; newline must be part of each string if needed.
Key Points
write()→ writes single stringwritelines()→ writes multiple strings from an iterable, no automatic newlines- Always include
\nin strings if a new line is needed“writelines(lines) writes a list or any iterable of strings to the stream. There is no separator or newline added automatically.”
75. After calling write(), data is first stored in:
A. RAM buffer
B. Hard disk directly
C. Stack memory
D. Output window
Answer: A. RAM buffer
Explanation
Explanation:
- In Python, file operations are buffered to improve performance.
- When
write()is called:
- The data is first stored in a memory buffer (RAM).
- Later, it is written to the physical file on disk either when:
- The file is closed using
close().flush()is explicitly called.- The buffer becomes full (depending on system and implementation).
- This buffering mechanism reduces frequent disk writes, improving efficiency.
Example
with open("demo.txt", "w") as f: f.write("Hello World") # Data goes to RAM buffer first f.flush() # Forces the buffer to write data to disk immediately
- Without
flush(), the data would still be written to disk automatically when the file is closed.Key Points
- Buffering stores data temporarily in RAM before writing to disk.
flush()can be used to manually write the buffer content.- Closing the file automatically flushes the buffer.
“BufferedWriter writes data to a memory buffer, which is then written to the underlying raw stream, improving efficiency.”
76. If a file is opened using 'a' mode and we write "Hello", then close it and reopen in 'r' mode — what happens?
A. File will be empty
B. Old data is erased
C. "Hello" will appear at the end of old content
D. File will show an error
Answer: C. "Hello" will appear at the end of old content
Explanation
Explanation:
- Append mode
'a'in Python:
- Opens a file for writing at the end of the file.
- Existing content is preserved.
- The file pointer is placed after the last character, so any new data is added after the old content.
- When the file is closed and reopened in read mode
'r', all content, including the newly appended"Hello", can be read.Example
Suppose
data.txtinitially contains:Line1 Line2# Append mode with open("data.txt", "a") as f: f.write("Hello\n") # Read mode with open("data.txt", "r") as f: print(f.read())Output:
Line1 Line2 Hello
"Hello"is added at the end.- Old content is not erased.
Key Points
'a'mode → append at end, preserves existing data.'w'mode → overwrite, erases existing content.- Always close the file to ensure data is written and saved.
“Opening a file in append mode'a'positions the file pointer at the end of the file. Data written is added after existing content.”
77. Which of the following is true about write() method?
A. It accepts numeric and string data both
B. It must be followed by flush()
C. It accepts only string arguments
D. It writes data line-by-line automatically
Answer: C. It accepts only string arguments
Explanation
Explanation:
- The
write()method in Python is used to write data to a file.- Important points about
write():
- Only string data is allowed.
- Numeric or other types must be converted using
str()before writing.- It does not automatically add newlines.
- If you need a newline, include
\nexplicitly.- It does not require
flush(), but callingflush()ensures data is immediately written from buffer to disk.Example
with open("demo.txt", "w") as f: f.write("Hello World\n") # Works f.write(str(123) + "\n") # Numeric converted to string # f.write(123) # TypeErrorContent of
demo.txt:Hello World 123Key Points
write()→ writes a single string to the file.- For multiple strings → use
writelines()or multiplewrite()calls.- Always include
\nif a new line is needed.“write(s) writes the string s to the stream. s must be a string, not an integer or other type.”
78. What will happen if we forget to close a file after using write()?
A. Data might remain unsaved in buffer
B. File automatically deletes
C. Python raises runtime error
D. File gets locked permanently
Answer: A. Data might remain unsaved in buffer
Explanation
Explanation:
- In Python, file operations are buffered for efficiency.
- When you use
write(), the data is first stored in a RAM buffer, not immediately written to disk.- If the file is not closed properly:
- Some data in the buffer may not be written to the file.
- This can lead to loss of recent writes.
- Proper ways to ensure data is written:
- Call
close()explicitly.- Use a
withstatement, which automatically closes the file at the end of the block.- Call
flush()to manually write the buffer to disk.Example
f = open("demo.txt", "w") f.write("Hello World") # Data goes to buffer # f.close() # If forgot, data may remain in buffer
- If the file is not closed,
"Hello World"may not appear indemo.txt.# Correct way with open("demo.txt", "w") as f: f.write("Hello World") # Automatically flushed and closedKey Points
- Always close files after writing to avoid data loss.
- Using
withstatement is recommended for safety.- Forgetting to close files can leave data in buffer, especially in large files or long-running programs.
“It is important to close the file after writing, otherwise buffered data may not be saved.”
79. The newline character \n in Python counts as how many characters when written to a file?
A. 0
B. 1
C. 2
D. Depends on OS
Answer: B. 1
Explanation
Explanation:
- In Python,
\nis a single character representing a newline.- When written to a file using
write():
- It moves the cursor to the next line.
- It is counted as one character in the total character count returned by
write().- Even though it creates a new line visually, internally it is just one character in the file.
Example
text = "Hello\nWorld" with open("demo.txt", "w") as f: chars_written = f.write(text) print(chars_written) # Output: 11
"Hello"→ 5 characters\n→ 1 character"World"→ 5 characters- Total = 11 characters
Key Points
\nis a single character in Python strings.- Always include
\nexplicitly if a new line is required in file writing.write()returns the total number of characters written, counting\nas 1.“\n represents a single newline character in strings.”
80. Which statement best describes the role of write() and writelines()?
A. Both read file data
B. Both write data to files
C. Both delete file data
D. Both close files
Answer: B. Both write data to files
Explanation
Explanation:
write():
- Writes a single string to a file.
- Returns the number of characters written.
- Newlines must be included explicitly using
\n.writelines():
- Writes multiple strings from an iterable (like a list or tuple) sequentially to a file.
- Does not automatically add newlines; they must be part of the strings.
- Both methods are used only for writing operations.
- Neither reads data, deletes data automatically, nor closes files; closing must be done explicitly or via a
withstatement.Example
# write() example with open("demo.txt", "w") as f: f.write("Hello\n") # writelines() example lines = ["Line1\n", "Line2\n", "Line3\n"] with open("demo.txt", "a") as f: f.writelines(lines)Content of
demo.txt:Hello Line1 Line2 Line3
write()→ wrote"Hello\n"writelines()→ wrote all strings in the list sequentiallyKey Points
write()→ writes one stringwritelines()→ writes multiple strings from an iterable- Both methods are writing operations only
“write() writes a single string to the stream. writelines() writes a sequence of strings to the stream.”
81. What does the writelines() method return?
A. Number of characters written
B. List of strings written
C. None
D. Boolean value
Answer: C. None
Explanation
Explanation:
writelines()writes all elements of an iterable (like a list or tuple) sequentially to a file.- Unlike
write(), it does not return the number of characters written.- Its return value is always
None.- Use
write()if you want to know how many characters were written.Example
lines = ["Line1\n", "Line2\n", "Line3\n"] with open("info.txt", "w") as f: result = f.writelines(lines) print(result) # Output: None
- All strings in
linesare written toinfo.txt.resultisNone— no count of characters is returned.Key Points
writelines()→ writes multiple strings, returns Nonewrite()→ writes single string, returns number of characters written- Always include
\nin strings if a newline is desired“writelines(lines) writes each element of the iterable to the stream. It returns None.”
82. Which of the following statements is true about writelines()?
A. It adds a newline after each string automatically
B. It can write multiple strings from an iterable
C. It returns the length of the iterable
D. It can only write one string
Answer: B. It can write multiple strings from an iterable
Explanation
Explanation:
writelines()writes all elements of an iterable (like a list or tuple) sequentially to a file.- Important points:
- It does not automatically add newlines; if you want line breaks, include
\nin the strings.- It can handle multiple strings at once.
- The method returns
None.- Only strings in the iterable are allowed; other data types must be converted using
str().Example
lines = ["Line1\n", "Line2\n", "Line3\n"] with open("info.txt", "w") as f: f.writelines(lines)Content of
info.txt:Line1 Line2 Line3
- All three strings are written sequentially.
- Newlines appear because
\nis explicitly included.Key Points
writelines()→ writes multiple strings from an iterable- No automatic newline insertion
- Returns
None“writelines(lines) writes each element of the given iterable to the stream. No separator or newline is added automatically.”
83. What will happen if a tuple of numbers is passed to writelines()?
A. Numbers are written as strings automatically
B. An error is raised
C. Only the first number is written
D. Numbers are converted to ASCII characters
Answer: B. An error is raised
Explanation
Explanation:
writelines()requires an iterable of strings (like a list or tuple of strings).- If you pass numbers (integers or floats) directly:
- Python cannot write them as-is.
- A
TypeErroris raised:"write() argument must be str, not int"- To write numbers, convert them to strings using
str()first.Example
numbers = (1, 2, 3) with open("demo.txt", "w") as f: # f.writelines(numbers) # Raises TypeError f.writelines([str(n) + "\n" for n in numbers]) # WorksContent of
demo.txtafter conversion:1 2 3
- Each number is converted to a string and written successfully.
Key Points
writelines()→ iterable of strings required- Numbers must be converted with
str()- Passing non-string types → TypeError
“Each element of the iterable must be a string. Otherwise, a TypeError is raised.”
84. What modes must a file be opened in to read its contents?
A. 'r', 'r+', 'w+', 'a+'
B. 'w', 'wb'
C. 'a' only
D. 'wb+' only
Answer: A. 'r', 'r+', 'w+', 'a+'
Explanation
Explanation:
- In Python, the mode in which a file is opened determines the operations allowed:
Mode Read Allowed Write Allowed Notes 'r'Yes No Read-only; file must exist 'r+'Yes Yes Read and write; file must exist 'w+'Yes Yes Read and write; overwrites file or creates new 'a+'Yes Yes Read and append; creates new if file doesn’t exist 'w'No Yes Write-only; overwrites file 'wb'No Yes Write-only binary mode
- Key point: Only modes that allow reading can be used to read file contents.
- Modes
'w'and'wb'are write-only, so reading is not allowed.Example
# Open file in 'r+' mode to read and write with open("demo.txt", "r+") as f: content = f.read() print(content)
'r+'allows both reading and writing.'w+'or'a+'would also allow reading, but'w+'overwrites existing content.Key Points
- To read file contents, use:
'r'→ read-only'r+'→ read/write'w+'→ read/write (overwrites file)'a+'→ read/append“Text files can be opened in modes that allow reading (r,r+,w+,a+). Write-only modes do not allow reading.”
85. What does the read(n) method do?
A. Reads the whole file irrespective of n
B. Reads n bytes from the file
C. Writes n bytes to the file
D. Deletes first n bytes from the file
Answer: B. Reads n bytes from the file
Explanation
Explanation:
read(n)is a method used to read data from a file.- Behavior:
- Reads
ncharacters (for text files) ornbytes (for binary files) from the current file pointer position.- If
nis omitted or negative, the entire file is read.- The file pointer moves forward by
ncharacters after reading.- This is useful when you want to read a portion of a file instead of loading the whole file into memory.
Example
with open("demo.txt", "r") as f: content = f.read(5) # Reads first 5 characters print(content)
- If
demo.txtcontains"Hello World", output will be:Hello
- The next call to
f.read(5)will read the next 5 characters:" Worl"Key Points
read(n)→ reads n characters/bytes from current pointer- File pointer advances automatically
- Use
read()without argument to read entire file“f.read(n) reads at most n characters (or bytes) from the file; if n is negative or omitted, the whole file is read.”
86. What is the output of the following code?
myfile = open("myfile.txt", "r")
print(myfile.read(10))
myfile.close()
If the file contains "Hello everyone".
A. Hello
B. Hello ever
C. Hello everyone
D. Error
Answer: B. Hello ever
Explanation
Explanation:
read(10)reads the first 10 characters from the file, which are"Hello ever".
read(n)readsncharacters from the current file pointer.- In the given code:
- File content:
"Hello everyone"read(10)→ reads first 10 characters from the start.- Counting characters:
Characters H e l l o (space) e v e r y o n e Position 1 2 3 4 5 6 7 8 9 10 11 12 13 14
- First 10 characters =
"Hello ever"- File pointer moves to the 11th character after reading.
Example Run
with open("myfile.txt", "r") as f: print(f.read(10))Output:
Hello everKey Points
read(n)→ reads exactlyncharacters (or fewer if end-of-file is reached)- File pointer advances automatically
- Useful for partial file reading
“f.read(n) reads at most n characters from the file; if the end of file is reached, fewer characters may be returned.”
87. What happens if read() is called with no arguments or a negative number?
A. Reads only the first line
B. Reads entire file content
C. Reads zero characters
D. Raises error
Answer: B. Reads entire file content
Explanation
Explanation:
read(n)readsncharacters from the current file pointer.- When
nis omitted or negative (-1):
- Python reads all remaining content from the current file pointer to the end of the file.
- This is useful when you want to load the whole file into memory at once.
Example
with open("demo.txt", "r") as f: content = f.read() # or f.read(-1) print(content)
- If
demo.txtcontains:Hello World Welcome to Python
- Output:
Hello World Welcome to Python
- The entire content is read in one call.
Key Points
read()without arguments → reads entire fileread(-1)→ behaves the same as no argument- File pointer moves to end of file after reading
“If n is omitted or negative, all data until EOF is read.”
88. Which of the following statements is correct?
A. writelines() adds newline characters automatically
B. read(n) can read negative characters
C. read() reads entire file if no argument is given
D. write() cannot write strings
Answer: C. read() reads entire file if no argument is given
Explanation
Explanation:
read()without any argument:
- Reads all content from the current file pointer to the end of file.
- Equivalent to
read(-1).- Important points about other methods:
writelines()→ Does not add newline characters automatically. Newlines must be part of the strings.read(n)→nmust be non-negative; negative values (or omission) read the entire file.write()→ Can write strings, but cannot write non-string types unless converted withstr().Example
with open("demo.txt", "r") as f: content = f.read() print(content)
- If
demo.txtcontains:Hello World Welcome to Python
- Output:
Hello World Welcome to Python
- The entire file content is read in a single call.
Key Points
read()with no argument → reads entire filewritelines()→ writes multiple strings, no automatic newlinewrite()→ writes strings onlyread(n)→ reads n characters“If no argument is provided toread(), the entire file is read from the current pointer.”
89. What is the correct way to read an entire file after opening it in 'r' mode?
A. file.read(0)
B. file.read(-1)
C. file.readlines(0)
D. file.read()
Answer: D. file.read()
Explanation
Explanation:
file.read()without arguments
- Reads the entire content of the file from the current file pointer position to the end of the file (EOF).
- The file pointer automatically moves to the end of file after reading.
- This is the standard method to read a whole file in NCERT examples.
Example Usage
with open("demo.txt", "r") as f: content = f.read() # Reads the entire file print(content)
- If
demo.txtcontains:Hello World Python File HandlingOutput:
Hello World Python File Handling
- The entire content is read and printed.
Key Points
read()without arguments → reads all remaining content from the current pointer.read(n)→ readsncharacters only.- Always use
read()when you want complete file content.“Callingread()without any argument reads the entire content of the file.”
“If no argument is provided toread(), all data is read until EOF.”
90. Consider the following code:
lines = ["Hello everyone\n", "Writing multiline strings\n", "This is the third line\n"]
myfile = open("myfile.txt", 'w')
myfile.writelines(lines)
myfile.close()
What will appear in myfile.txt when opened in Notepad?
A. All strings concatenated without line breaks
B. Each string on a separate line
C. Only the first line
D. Error
Answer: B. Each string on a separate line
Explanation
Explanation:
- About the code:
- A list named
linesis created containing three strings.- Each string ends with a newline character
\n.- The file is opened in write mode
'w', which creates a new file or overwrites an existing one.writelines(lines)writes each string in the list to the file sequentially.close()saves and closes the file properly.- How writelines() works:
- It writes each element of the iterable (like list or tuple) to the file exactly as it is given.
- It does not add newline characters automatically, so you must include
\nmanually if you want each string to appear on a new line.- Since each string already ends with
\n, the content inmyfile.txtwill appear as:Hello everyone Writing multiline strings This is the third lineKey Concept Recap
Method Description Automatically adds \n?write()Writes a single string No writelines()Writes multiple strings from an iterable No (need to include \nmanually)“Thewritelines()function writes a sequence of strings to a file. It does not add newline characters automatically.”
91. What will happen if the \n is omitted from strings in writelines()?
A. Strings will be written on the same line
B. Strings will be automatically separated
C. File will raise an error
D. Only first string will be written
Answer: A. Strings will be written on the same line
Explanation
Explanation:writelines() does not add newlines. Without \n, all strings are written consecutively on a single line.
92. Which of the following modes allows reading after appending data to a file?
A. 'w'
B. 'a'
C. 'a+'
D. 'wb'
Answer: C. 'a+'
Explanation
Explanation:
- The
'a+'mode in Python opens the file for both appending and reading.- The file pointer is positioned at the end of the file when opened.
- You can append new data at the end and also read data (after moving the pointer if needed using
seek()).Example:
f = open("file.txt", "a+") f.write("New data\n") f.seek(0) print(f.read()) f.close()This code appends text and then reads the entire file successfully.
Why other options are incorrect:
Mode Meaning Read Allowed? Append Allowed? 'w'Write only No No 'a'Append only No Yes 'a+'Append + Read Yes Yes 'wb'Binary Write No No
93. Which of the following is true about read() and read(n)?
A. read(n) returns a list of strings
B. read() reads entire file, read(n) reads n bytes
C. read() cannot read text files
D. read(n) writes n bytes
Answer: B. read() reads entire file, read(n) reads n bytes
Explanation
Explanation:
- The
read()method is used to read the contents of a file in text or binary mode.- When called without arguments, it reads the entire remaining content of the file.
- When called with an argument
n, it reads exactlyncharacters (in text mode) or n bytes (in binary mode) from the current file pointer.Example 1:
f = open("sample.txt", "r") print(f.read(5)) # Reads first 5 characters print(f.read()) # Reads the rest of the file f.close()If file contains:
Python File HandlingOutput:
Pytho n File HandlingKey Points:
read()with no argument → reads entire file.read(n)→ reads exactlyncharacters or bytes.- Both return a string (in text mode), not a list.
- After reading, the file pointer moves forward by
npositions.“Theread()function reads the whole file, whereasread(n)reads onlyncharacters (or bytes in binary mode) starting from the current file pointer.”
94. Which of the following is incorrect?
A. read() moves the file pointer
B. writelines() returns number of characters
C. read(n) reads n characters
D. writelines() can write multiple strings
Answer: B. writelines() returns number of characters
Explanation
Explanation:
A.
read()moves the file pointerWhen
read()orread(n)is called on a file, the file pointer automatically moves forward by the number of characters (or bytes) read. This pointer indicates where the next read or write operation will start.Example:
f = open("demo.txt", "r") data = f.read(5) print(f.tell()) # Output: 5 f.close()Here,
f.tell()shows that the pointer has moved to position 5 after reading 5 characters.B.
writelines()returns number of charactersThis statement is incorrect. The
writelines()method does not return any value. It only writes all strings from an iterable (like a list or tuple) to the file. Its return value is alwaysNone.Example:
f = open("demo.txt", "w") result = f.writelines(["Hello", "World"]) print(result) f.close()Output:
NoneC.
read(n)reads n charactersThe
read(n)method reads exactly n characters (or n bytes in binary mode) from the current file pointer position. If fewer than n characters remain, it reads until the end of the file.Example:
f = open("demo.txt", "r") print(f.read(6)) f.close()If the file contains
"Python", the output will be:PythonD.
writelines()can write multiple stringsThe
writelines()method writes all elements from an iterable of strings to the file sequentially. It does not add newline characters automatically; if line breaks are required,\nmust be included in the strings.Example:
lines = ["Line1\n", "Line2\n", "Line3\n"] f = open("data.txt", "w") f.writelines(lines) f.close()File content:
Line1 Line2 Line3Final Conclusion
Option Statement Correctness Explanation A read()moves the file pointerCorrect Pointer moves automatically after reading B writelines()returns number of charactersIncorrect Returns None, not character count C read(n)reads n charactersCorrect Reads n characters or bytes D writelines()can write multiple stringsCorrect Writes all strings from an iterable
95. What happens if a file is opened in 'r' mode but does not exist?
A. File is created
B. File pointer is at end
C. Raises FileNotFoundError
D. File is empty
Answer: C. Raises FileNotFoundError
Explanation
Explanation:
- The
'r'mode in Python is used for reading an existing file.- It requires the file to exist before opening.
- If the file does not exist, Python cannot read it, and hence it raises a
FileNotFoundError.- The
'r'mode does not create a new file automatically.Example:
f = open("nonexistent.txt", "r")Output:
FileNotFoundError: [Errno 2] No such file or directory: 'nonexistent.txt'
- To create a new file if it doesn’t exist, you would use
'w','a', or'x'modes instead.- The
'r+'mode also requires the file to exist, otherwise it raises the same error.“When a file is opened in read mode ('r'), it must exist. If it does not, Python raises an exception.”
96. What does readline(n) do in Python?
A. Reads entire file
B. Reads first n characters of the first line (up to newline)
C. Reads n lines from the file
D. Writes n characters to the file
Answer: B. Reads first n characters of the first line (up to newline)
Explanation
Explanation:
- The
readline()method in Python is used to read a single line from a file.- The optional parameter
nspecifies the maximum number of characters to read from that line.- If the newline character (
\n) is encountered before reaching n characters,readline(n)stops reading and returns the characters including the newline.- If the line has fewer than n characters, the entire line is returned.
Example 1: Without n
f = open("demo.txt", "r") line = f.readline() print(line) f.close()
- Output: Returns the first line entirely, including
\n.Example 2: With n
f = open("demo.txt", "r") line = f.readline(5) print(line) f.close()
- Output: Returns at most first 5 characters of the first line, or less if a newline occurs sooner.
Key Points:
- Only reads one line at a time.
readline()withndoes not read multiple lines; it stops at the newline or after n characters.“Thereadline()method reads one line at a time. An optional argument n specifies the maximum number of characters to read from that line.”
97. What does readline() without any argument return?
A. Nothing
B. One complete line including the newline character
C. Entire file content
D. List of strings
Answer: B. One complete line including the newline character
Explanation
Explanation:
- The
readline()method reads one line at a time from the file.- When called without any argument, it reads the entire line from the current file pointer position until the newline character (
\n) is encountered.- The returned string includes the newline character at the end of the line (except for the last line if the file does not end with
\n).readline()does not read the entire file; multiple calls are required to read successive lines.Example:
f = open("demo.txt", "r") line = f.readline() print(repr(line)) f.close()If the first line of
demo.txtis:Hello WorldOutput:
'Hello World\n'Key Points:
- Returns a string, not a list.
- To read all lines into a list, use
readlines()instead.- Each call to
readline()advances the file pointer to the start of the next line.“Thereadline()method reads a single line including the trailing newline character.”
98. What is returned by readline() when EOF (End of File) is reached?
A. 'EOF'
B. Empty string ''
C. None
D. Raises error
Answer: B. Empty string ''
Explanation
Explanation:
- The
readline()method reads a single line from a file.- When the file pointer reaches the end of the file, there are no more lines to read.
- In this case,
readline()returns an empty string ('').- This behavior is useful when iterating through a file line by line, allowing loops to stop when EOF is reached.
Example:
f = open("demo.txt", "r") while True: line = f.readline() if line == '': break print(line, end='') f.close()
- The loop terminates when
readline()returns''at the end of the file.Key Points:
readline()does not raise an error at EOF.- Returning
''differentiates between an actual empty line ('\n') and the end of file.“Thereadline()method returns an empty string when the end of file is reached.”
99. Consider the following code:
myfile = open("myfile.txt", "r")
print(myfile.readline(10))
myfile.close()
If the first line of myfile.txt is "Hello everyone\n", the output will be:
A. Hello ever
B. Hello everyon
C. Hello everyone
D. Hello
Answer: A. Hello ever
Explanation
Explanation:
- The
readline(n)method reads up to n characters from the current line.- If a newline character (
\n) occurs before n characters, reading stops there. Otherwise, it reads exactly n characters.- In this example:
- The first line is
"Hello everyone\n"readline(10)reads the first 10 characters starting from the beginning:"Hello ever"Character counting for clarity:
H e l l o e v e r y o n e \n 1 2 3 4 5 6 7 8 9 10 ...
- The first 10 characters are
"Hello ever".- To read the entire line, you can use
readline()without any argument.Example for reading the full line:
f = open("myfile.txt", "r") print(f.readline()) f.close()
- Output:
"Hello everyone\n"“Thereadline(n)method reads at most n characters from the current line, including the newline character if it occurs before n characters.”
100. Which of the following is correct about iterating over a file object using readline()?
A. Returns a list of lines
B. Returns one line at a time
C. Reads entire file at once
D. Writes lines to another file
Answer: B. Returns one line at a time
Explanation
Explanation:
- The
readline()method is used to read one line at a time from a file.- When iterating over a file using a loop with
readline(), each iteration returns the next line until the end of the file (EOF) is reached.- This is useful when processing large files line by line, as it avoids loading the entire file into memory at once.
Example:
f = open("demo.txt", "r") while True: line = f.readline() if line == '': break print(line, end='') f.close()
- Here,
readline()reads each line sequentially.- The loop stops when
readline()returns an empty string'', indicating EOF.Key Points:
readline()returns a string, not a list.- To read all lines at once into a list,
readlines()should be used.- Each call to
readline()advances the file pointer to the start of the next line.“Usingreadline()in a loop allows reading a file one line at a time, which is efficient for processing large files.”
101. What does the readlines() method return?
A. Entire file as a single string
B. A list of strings where each element is a line
C. One line at a time
D. Number of lines in the file
Answer: B. A list of strings where each element is a line
Explanation
Explanation:
- The
readlines()method reads the entire file from the current file pointer position.- It returns a list of strings, where each element corresponds to one line of the file, including the newline character
\n.- This method is useful when you want to process all lines at once.
Example:
f = open("demo.txt", "r") lines = f.readlines() print(lines) f.close()If
demo.txtcontains:Line 1 Line 2 Line 3Output:
['Line 1\n', 'Line 2\n', 'Line 3\n']Key Points:
- Unlike
readline(), which returns one line at a time,readlines()returns all lines at once as a list.- Newline characters are preserved; if you want to remove them, you can use
strip()or list comprehension.“Thereadlines()method reads all lines of a file and returns them as a list of strings.”
102. Which of the following is true?
A. readlines() automatically removes \n
B. readlines() returns strings including newline characters
C. readlines() returns integers
D. readlines() can write data
Answer: B. readlines() returns strings including newline characters
Explanation
Explanation:
- The
readlines()method reads all lines from a file and returns them as a list of strings.- Each line in the list includes the newline character (
\n) at the end (except possibly the last line if the file does not end with a newline).- This behavior differentiates it from methods that process lines without including
\n.Example:
f = open("demo.txt", "r") lines = f.readlines() print(lines) f.close()If
demo.txtcontains:Hello World PythonOutput:
['Hello\n', 'World\n', 'Python\n']Key Points:
readlines()does not remove newline characters automatically.- Each element of the returned list is a string representing one line of the file.
- To remove
\n, you can use a list comprehension:lines = [line.strip() for line in f.readlines()]“Thereadlines()method reads all lines of a file and returns them as a list of strings, including newline characters.”
103. What will the following code output?
myfile = open("myfile.txt", "r")
lines = myfile.readlines()
print(lines)
myfile.close()
If myfile.txt contains:
Hello
Python
File Handling
A. 'Hello\nPython\nFile Handling\n'
B. ['Hello\n', 'Python\n', 'File Handling\n']
C. ['Hello', 'Python', 'File Handling']
D. Hello Python File Handling
Answer: B. ['Hello\n', 'Python\n', 'File Handling\n']
Explanation
Explanation:
- The
readlines()method reads all lines from the file and returns them as a list of strings.- Each string in the list includes the newline character (
\n) at the end, except possibly the last line if the file does not end with a newline.- In this example:
- Line 1 →
'Hello\n'- Line 2 →
'Python\n'- Line 3 →
'File Handling\n'Output:
['Hello\n', 'Python\n', 'File Handling\n']Key Points:
readlines()differs fromread()(which returns the entire file as a single string) andreadline()(which returns one line at a time).- The newline characters are preserved unless explicitly removed using
strip()or list comprehension.Example to remove
\n:lines = [line.strip() for line in myfile.readlines()]“Thereadlines()method returns all lines of the file as a list of strings, including newline characters.”
104. Which method would you use to read a file line by line without loading the entire file into memory?
A. read()
B. readline()
C. readlines()
D. write()
Answer: B. readline()
Explanation
Explanation:
- The
readline()method reads one line at a time from a file.- This is memory-efficient, especially for large files, because it does not load the entire file into memory.
- In contrast,
readlines()reads all lines at once and stores them in a list, which can be memory-intensive for large files.read()reads the entire file as a single string, which also consumes more memory.write()is used to write data to a file, not for reading.Example of reading large file line by line:
with open("largefile.txt", "r") as f: while True: line = f.readline() if line == '': break print(line, end='')
- Each iteration reads only one line.
- The loop stops when
readline()returns an empty string'', indicating the end of the file.Key Points:
readline()is ideal for processing files line by line.- It helps avoid memory overflow when dealing with large files.
“Thereadline()method reads a single line at a time, making it suitable for large files where memory usage is a concern.”
105. Which of the following statements about readline(n) is correct?
A. It reads exactly n lines
B. It reads up to n characters of the current line
C. It reads the whole file if n is negative
D. It writes n characters
Answer: B. It reads up to n characters of the current line
Explanation
Explanation:
- The
readline(n)method reads at most n characters from the current line in a file.- Reading stops earlier if a newline character (
\n) is encountered before reaching n characters.- It does not read multiple lines; only the current line is affected.
- If
nis omitted,readline()reads the entire line.Example:
f = open("demo.txt", "r") line = f.readline(5) print(line) f.close()If
demo.txtcontains:Hello World
readline(5)outputs:Hello
- Only the first 5 characters of the first line are read.
Key Points:
readline(n)is different fromreadlines(), which reads all lines into a list.- Useful when you want partial reading of a line, e.g., for parsing large files line by line.
“Thereadline(n)method reads at most n characters from the current line, stopping at the newline character if encountered before n characters.”
106. What happens if readlines() is called on an empty file?
A. Returns None
B. Returns an empty list []
C. Raises FileNotFoundError
D. Returns a list with empty string [”]
Answer: B. Returns an empty list []
Explanation
Explanation:
- The
readlines()method reads all lines from the current file pointer position and returns them as a list of strings.- If the file is empty, there are no lines to read.
- In this case,
readlines()returns an empty list[], indicating the file contains no content.- It does not return
Noneand does not raise any error.Example:
f = open("empty.txt", "r") lines = f.readlines() print(lines) f.close()Output:
[ ]Key Points:
- An empty file always results in an empty list when using
readlines().- This behavior is useful for checking whether a file has any content before processing.
“If the file has no lines, thereadlines()method returns an empty list[].”
107. Which of the following is false about readline()?
A. Reads one line at a time
B. Stops at newline character
C. Returns empty string at EOF
D. Returns a list of lines
Answer: D. Returns a list of lines
Explanation
Explanation:
readline()Python ka ek file object method hai jo file se ek line ko string ke roop me read karta hai.
- Ye method newline character (
\n) tak line read karta hai aur us line ko string me return karta hai.- Agar file ka end (EOF) aajaye, to
readline()empty string ("") return karta hai, jo batata hai ki file me aur content nahi hai.readline()ek string return karta hai, list nahi. Agar aapko file ki saari lines ek list me chahiye, toreadlines()method use hota hai.Example:
f = open("example.txt", "r") print(f.readline()) # Output: 'Hello\n' print(f.readline()) # Output: 'World\n' print(f.readline()) # Output: 'Python\n' print(f.readline()) # Output: '' (empty string at EOF)"f.readline() reads one entire line from the file. A trailing newline character is kept in the string. Returns an empty string when EOF is reached."
108. What is a common use of split() after readlines()?
A. To convert each line to a number
B. To display each word separately as list elements
C. To remove newline characters automatically
D. To reverse file contents
Answer: B. To display each word separately as list elements
Explanation
Explanation:
Thereadlines()method reads all lines from a file and stores them in a list of strings, where each element corresponds to one line, often including the newline character (\n).After reading the lines, the
split()method can be applied to each line.split()divides a string into words based on whitespace and returns them as a list. This allows each word in a line to be accessed individually as elements of a list.Example:
f = open("example.txt", "r") lines = f.readlines() # ['Hello world\n', 'Python programming\n'] for line in lines: words = line.split() print(words)Output:
['Hello', 'world'] ['Python', 'programming']Here,
split()converts each line into a list of words, which is a common practice for processing text data word by word."The split() method returns a list of the words in the string, using whitespace as the default separator."
109. How can you iterate over a file object to read lines without readline() or readlines()?
A. Using a for loop directly on the file object
B. Using write()
C. Using close()
D. Using append()
Answer: A. Using a for loop directly on the file object
Explanation
Explanation:
In Python, file objects are iterable, which means you can loop over them directly using aforloop. Each iteration of the loop returns the next line in the file as a string, including the newline character (\n). This method is memory-efficient because it reads one line at a time rather than loading the entire file into memory (unlikereadlines()).Example:
f = open("example.txt", "r") for line in f: print(line, end='') # Prints each line of the file
- Here,
for line in f:automatically reads the file line by line.- It avoids the need to use
readline()orreadlines()explicitly.- This approach is particularly useful for large files, where reading all lines at once may be memory-intensive.
"File objects are iterable, so you can loop over the file object to read lines one by one."
110. Which of the following will not preserve the newline character?
A. readlines()
B. readline()
C. splitlines()
D. Iterating with for line in file:
Answer: C. splitlines()
Explanation
Explanation:
- The
splitlines()method splits a string into a list of lines without including the newline character (\n) at the end of each line.- This makes it different from
readline()orreadlines(), which preserve the newline character in the returned string(s).- Similarly, iterating over a file using
for line in file:also preserves the newline character.Example:
f = open("example.txt", "r") content = f.read() lines = content.splitlines() print(lines)
- If
example.txtcontains:Hello World Python
- The output will be:
['Hello', 'World', 'Python']
- Notice that the newline characters (
\n) are removed bysplitlines()."Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends=True."
111. What does the split() method do when used on a line read from a file?
A. Splits the line into characters
B. Splits the line into words based on whitespace
C. Splits the file into lines
D. Removes newline characters
Answer: B. Splits the line into words based on whitespace
Explanation
Explanation:
- The
split()method in Python is used on strings to divide them into a list of substrings.- When called without any arguments,
split()uses whitespace (space, tab, newline) as the default delimiter.- This is commonly applied to a line read from a file (using
readline()or iterating over the file) to break the line into individual words for further processing.Example:
line = "Python programming is fun\n" words = line.split() print(words)Output:
['Python', 'programming', 'is', 'fun']
- Here,
split()ignores the newline character (\n) and splits the line into words."The split() method returns a list of the words in the string, using whitespace as the default separator."
112. Consider the following code:
for line in d:
words = line.split()
print(words)
If d contains:
Hello everyone
Writing multiline strings
This is the third line
What will be the output of the first iteration?
A. ['Hello', 'everyone']
B. ['Hello everyone']
C. 'Hello'
D. ['H','e','l','l','o']
Answer: A. ['Hello', 'everyone']
Explanation
Explanation:
- In the first iteration,
linewill contain the first line of the file or listd:"Hello everyone"
- Applying
split()on this line divides the string at whitespace by default.- Therefore,
"Hello everyone".split()results in a list of words:['Hello', 'everyone']
- This list is then printed by
print(words).Example Demonstration:
d = ["Hello everyone", "Writing multiline strings", "This is the third line"] for line in d: words = line.split() print(words)Output of first iteration:
['Hello', 'everyone']
split()does not split into characters (like option D) and keeps each word as a separate element in the list."The split() method returns a list of the words in the string, using whitespace as the default separator."
113. What is the difference between split() and splitlines()?
A. split() splits lines into words, splitlines() splits file into lines
B. split() removes newline, splitlines() keeps newline
C. Both behave the same
D. splitlines() splits line into words
Answer: A. split() splits lines into words, splitlines() splits file into lines
Explanation
Explanation:
split()method:
- Operates on a string and splits it into a list of words based on whitespace (by default) or a specified delimiter.
- Example:
line = "Hello world" words = line.split() print(words)Output:
['Hello', 'world']
splitlines()method:
- Operates on a string and splits it into lines, returning a list of strings, without the newline character (
\n).- Example:
text = "Hello world\nPython programming\n" lines = text.splitlines() print(lines)Output:
['Hello world', 'Python programming']
- Key difference:
split()→ splits a line into words.splitlines()→ splits a multi-line string into lines."split()divides a string into words using a delimiter;splitlines()divides a string into lines and removes the newline characters."
114. What will be the output of splitlines() on the line "Hello everyone\n"?
A. ['Hello', 'everyone']
B. ['Hello everyone']
C. 'Hello everyone'
D. ['H','e','l','l','o']
Answer: B. ['Hello everyone']
Explanation
Explanation:
- The
splitlines()method splits a string at line boundaries (like\n,\r\n) and returns a list of strings.- Importantly, it removes the newline characters (
\n) from the resulting list.- Here,
"Hello everyone\n"contains only one line, sosplitlines()returns a list with that single line as an element, without the\n.Example:
line = "Hello everyone\n" result = line.splitlines() print(result)Output:
['Hello everyone']
- It does not split words; that’s what
split()does.- The newline character is removed in the resulting list.
"Return a list of the lines in the string, breaking at line boundaries. Line breaks are not included in the resulting list unless keepends=True."
115. Which mode is used to write user input into a text file in Program 2-1?
A. 'r'
B. 'w'
C. 'a'
D. 'rb'
Answer: B. 'w'
Explanation
Explanation:
- In Python, file modes determine how a file is opened.
- The mode
'w'stands for write mode:
- If the file already exists, opening it in
'w'mode overwrites the existing content.- If the file does not exist, a new file is created.
- This mode is used in Program 2-1 to write user input into a text file, replacing any existing content if the file already exists.
Example:
f = open("example.txt", "w") f.write("Hello World\n") f.close()
- After execution,
example.txtwill contain:Hello World"Mode 'w' opens a file for writing. If the file exists, it is truncated. If it does not exist, it is created."
116. What will happen if the file testfile.txt already exists in Program 2-1?
A. It will append the new input
B. It will overwrite existing content
C. It will raise an error
D. It will read existing content first
Answer: B. It will overwrite existing content
Explanation
Explanation:
- In Program 2-1, the file is opened in write mode (
'w').- Write mode (
'w') behavior:
- If the file already exists, opening it in
'w'truncates the file, i.e., all existing content is erased.- If the file does not exist, a new file is created.
- Therefore, if
testfile.txtexists, all its previous content will be overwritten with the new input provided by the user.Example:
# Existing file content: "Old Data" f = open("testfile.txt", "w") f.write("New Data") f.close()
- After execution,
testfile.txtwill contain:New Data
- The previous content
"Old Data"is lost."Mode 'w' opens a file for writing. If the file exists, it is truncated. If it does not exist, it is created."
117. In Program 2-1, which method writes the user input to the file?
A. read()
B. write()
C. readlines()
D. split()
Answer: B. write()
Explanation
Explanation:
- In Python, the
write()method is used to write a string to a file at the current file pointer position.- When the file is opened in write mode (
'w'),write()can store user input into the file.- Unlike
read()orreadlines(), which read data from a file,write()is specifically for outputting text to a file.Example:
f = open("testfile.txt", "w") f.write("Hello World\n") f.close()
- After execution,
testfile.txtwill contain:Hello World
- The string is written exactly as provided, at the beginning of the file if
'w'mode is used."write(string) writes the contents of string to the file. Returns the number of characters written."
118. In Program 2-1, how is the file read after writing?
A. Using read()
B. Using for str in fobject: loop
C. Using writelines()
D. Using split()
Answer: B. Using for str in fobject: loop
Explanation
Explanation:
- In Python, file objects are iterable, which allows you to loop directly over the file using a
forloop.- Each iteration of the loop reads the next line from the file, including the newline character (
\n).- This method is memory-efficient because it reads one line at a time, instead of loading the entire file into memory (as
read()orreadlines()would do).- In Program 2-1, after writing user input to the file, the file is reopened in read mode, and a loop like
for line in f:is used to display the contents line by line.Example:
f = open("testfile.txt", "r") for line in f: print(line, end='') # Prints each line from the file f.close()
- Each iteration of
for line in f:gives one line as a string, which can then be processed or displayed."File objects are iterable, so you can loop over the file object to read lines one by one efficiently."
119. Why is fobject.close() used after writing to the file?
A. To delete the file
B. To free system resources and flush buffer
C. To append more data
D. To read the file
Answer: B. To free system resources and flush buffer
Explanation
Explanation:
- The
close()method is used to close a file object after all file operations are complete.- When writing to a file, Python buffers the data in memory for efficiency.
fobject.close()ensures that:
- All buffered data is written to the file.
- System resources associated with the file are released.
- Failing to close a file may result in data not being saved properly or resources remaining allocated unnecessarily.
Example:
f = open("testfile.txt", "w") f.write("Hello World\n") f.close() # Ensures data is flushed and file is properly closed
- After
close(), the file is safely written and no longer locked by the program."close() flushes the write buffer of the file and releases system resources associated with it."
120. What will happen if close() is not called after writing in Program 2-1?
A. Data may not be written to file completely
B. File will be deleted automatically
C. File pointer moves to beginning
D. Python raises error
Answer: A. Data may not be written to file completely
Explanation
Explanation:
- In Python, writing to a file is buffered, meaning data is temporarily stored in memory before being written to disk.
- If
close()is not called, the buffered data may not be completely written to the file.- Calling
close()ensures that:
- All buffered data is flushed to the disk.
- The file is properly closed, and system resources are released.
- Failing to close the file may result in partial or lost data, especially when writing large amounts of data.
Example:
f = open("testfile.txt", "w") f.write("Hello World\n") # f.close() is missing
- Without
close(), the text"Hello World\n"might not be fully saved totestfile.txt.- Using
with open(...) as f:is a better practice as it automatically closes the file."Buffered output may not be written to disk until the file is closed. close() flushes the buffer and releases system resources."
121. Which of the following correctly describes the flow of Program 2-1?
A. Read file → Write user input → Close file
B. Write user input → Close file → Open for reading → Iterate lines
C. Open file → Append → Read → Split lines
D. Close file → Write → Read
Answer: B. Write user input → Close file → Open for reading → Iterate lines
Explanation
Explanation:
- Program 2-1 Flow:
- Write user input: The program opens the file in write mode (
'w') and writes the input provided by the user.- Close file: The file is closed using
close()to flush the buffer and release system resources.- Open for reading: The file is reopened in read mode (
'r') to access its contents.- Iterate lines: The program uses a for loop over the file object to read and display lines one by one efficiently.
- This ensures data integrity, as writing is completed and resources are released before reading begins.
Example Flow:
# Write user input f = open("testfile.txt", "w") f.write("Hello World\n") f.close() # Read file f = open("testfile.txt", "r") for line in f: print(line, end='') f.close()Output:
Hello World
- The program follows the sequence described in option B.
"To write and read from a file safely, open in write mode, close the file, then reopen in read mode to access the content."
122. What type of object is returned by open()?
A. String
B. File object
C. List
D. Integer
Answer: B. File object
Explanation
Explanation:
- The
open()function in Python is used to open a file and returns a file object.- A file object represents the connection between the program and the file, and it provides methods to read from or write to the file.
- The file object can be used with methods such as:
read()– to read file contentwrite()– to write to the filereadline()/readlines()– to read linesclose()– to close the fileExample:
f = open("testfile.txt", "r") print(type(f)) f.close()Output:
<class '_io.TextIOWrapper'>
- This shows that
open()returns a file object (in Python, typically_io.TextIOWrapperfor text files)."open() returns a file object, which provides methods and attributes to interact with the file."
123. What will for str in fobject: do in Program 2-1?
A. Iterate over words
B. Iterate over lines
C. Iterate over characters
D. Split lines automatically
Answer: B. Iterate over lines
Explanation
Explanation:
- In Python, file objects are iterable, which allows a
forloop to iterate line by line.- Each iteration returns one line as a string, including the newline character (
\n) at the end.- This method is memory-efficient, as it does not load the entire file into memory like
readlines().Example:
f = open("testfile.txt", "r") for line in f: print(line, end='') f.close()
- If
testfile.txtcontains:Hello World Python Programming
- Output:
Hello World Python Programming
- Each iteration of
for line in f:gives one line at a time, which can then be processed or printed."File objects are iterable. Iterating over a file object returns one line at a time."
124. What happens if input() is empty in Program 2-1?
A. Writes a blank line to the file
B. Raises error
C. Does not create the file
D. Writes default string
Answer: A. Writes a blank line to the file
Explanation
Explanation:
In Python, the
input()function reads user input as a string.
If the user simply presses Enter without typing anything,input()returns an empty string ("").Consider this part of Program 2-1 (from NCERT):
myfile = open("poem.txt", "w") line = input("Enter text: ") myfile.write(line) myfile.close()If the user presses Enter without typing anything,
linebecomes an empty string ("").- When
myfile.write(line)executes, it writes exactly what is passed — in this case, an empty string.If the user pressed Enter (which includes a newline), the file will show a blank line (i.e., just a
\n).Hence, the file
poem.txtwill contain a blank line, not an error or default value.Concept Recap:
write()writes exactly the given string — even if it’s empty.- No error occurs when writing an empty string.
- File creation depends only on the
open()function, not on the content written.“Write the given string to the stream. Returns the number of characters written.”
125. Which of the following can be used to display each word separately from a line read from the file?
A. splitlines()
B. split()
C. readlines()
D. write()
Answer: B. split()
Explanation
Explanation:
When a line is read from a file usingreadline()or by iterating over the file object, it is received as a string.
To separate and display each word from that line, we use thesplit()method.For example:
line = "Python is fun" words = line.split() print(words)Output:
['Python', 'is', 'fun']The
split()method divides a string at whitespace (space, tab, or newline) and returns a list of individual words. You can also specify a custom delimiter likesplit(',')if the words are separated by commas.In contrast, other methods such as
splitlines()divide text by lines, not by words;readlines()reads multiple lines from a file as list elements; andwrite()is used to write data into a file, not to process or display it.Hence, only
split()correctly separates words from a single line read from a file.“Return a list of the words in the string, using sep as the delimiter string.”
126. What does tell() method return?
A. Number of lines in a file
B. Current byte position of the file object
C. Total size of the file
D. File name
Answer: B. Current byte position of the file object
Explanation
Explanation:
In Python, every file object maintains a file pointer that indicates the current position (in bytes) within the file.
Thetell()method returns an integer value that represents the number of bytes from the beginning of the file up to the current position of this pointer.For example:
f = open("data.txt", "r") pos = f.tell() print(pos)If the file pointer is at the start of the file,
tell()will return0.
After reading or writing some data, the file pointer moves forward, and callingtell()again will return a larger value corresponding to that byte position.Thus,
tell()helps track where the next read or write operation will occur.It does not return the number of lines, file name, or total size of the file — only the current byte offset.
127. Which of the following is correct about seek(offset, reference_point)?
A. Moves the file pointer to a specific line number
B. Moves the file pointer by offset from the reference point
C. Writes data at the specified position
D. Deletes bytes at the specified offset
Answer: B. Moves the file pointer by offset from the reference point
Explanation
Explanation:
Theseek(offset, reference_point)method in Python is used to move the file pointer (also called the file cursor) to a new position, allowing random access within a file.Its syntax is:
file_object.seek(offset, reference_point)
offset→ number of bytes to move the pointer.reference_point→ starting position from where movement is measured:
0→ beginning of the file (default)1→ current position2→ end of the fileFor example:
f = open("data.txt", "rb") f.seek(10, 0) # moves pointer 10 bytes from start position = f.tell() print(position)This will display
10, meaning the file pointer is now 10 bytes from the beginning.Hence,
seek()does not write or delete data, nor does it move by line numbers — it moves by byte positions, based on the given reference point.
128. What is the default value of the reference_point in seek()?
A. 0 (beginning of file)
B. 1 (current position)
C. 2 (end of file)
D. None
Answer: A. 0 (beginning of file)
Explanation
Explanation:
Theseek()method in Python moves the file pointer (cursor) to a specific position in the file.
Its general syntax is:file_object.seek(offset, reference_point)Here,
offset→ number of bytes to move, andreference_point→ the position from which the movement is calculated.If you don’t specify the
reference_point, Python automatically assumes it to be0, which represents the beginning of the file.
This means thatseek(offset)is equivalent toseek(offset, 0).For example:
f = open("example.txt", "rb") f.seek(5) # same as f.seek(5, 0) print(f.tell())This moves the file pointer 5 bytes from the start of the file.
As per the Python official documentation,
“The whence argument defaults to 0, which means absolute file positioning (from the start of the file).”Hence,
seek()by default counts the byte offset from the beginning of the file unless another reference point is provided
129. In the statement fileObject.seek(5,0), what does 5 signify?
A. Move 5 bytes from current position
B. Move 5 bytes from end of file
C. Move 5 bytes from beginning of file
D. Move 5 lines from beginning
Answer: C. Move 5 bytes from beginning of file
Explanation
Explanation:
In Python, theseek(offset, reference_point)method repositions the file pointer within a file.
Here:
offsetspecifies how many bytes to move, andreference_point(also calledwhence) specifies from where the movement starts.In the statement:
fileObject.seek(5, 0)
- The
5is the offset, meaning the pointer should move 5 bytes ahead.- The
0(reference point) represents the beginning of the file.So this command moves the file pointer 5 bytes from the start of the file.
After executing it, callingfileObject.tell()will return5, showing the pointer’s new position.It does not move by lines, nor from the current or end positions—movement is always in bytes.
As per the Python official documentation,
“The whence argument defaults to 0, which means absolute file positioning (from the start of the file).”Hence, in
seek(5, 0), the number5signifies the byte offset from the file’s beginning.
130. Which reference_point value moves the pointer relative to the current file position?
A. 0
B. 1
C. 2
D. None
Answer: B. 1
Explanation
Explanation:
In Python’s file handling, the
seek(offset, reference_point)method allows you to move the file pointer to a specific position within a file.
Here, thereference_point(also calledwhence) determines from where the movement begins:
Reference Point Value Meaning 0Beginning of file Absolute positioning 1Current position Relative positioning 2End of file Relative to file end When we write:
fileObject.seek(offset, 1)the file pointer moves
offsetbytes forward or backward (if negative) from its current position.Example:
f = open("data.txt", "rb") f.seek(10, 0) # move to byte 10 from start f.seek(5, 1) # move 5 bytes ahead from current position (byte 15) print(f.tell()) # Output: 15Thus, when the
reference_pointis 1,seek()performs movement relative to the current file position, enabling precise navigation inside the file.As per the Python official documentation,
“The whence argument can be 0 (absolute file positioning), 1 (seek relative to the current position), or 2 (seek relative to the file’s end).”
131. Which reference_point value moves the pointer relative to the end of file?
A. 0
B. 1
C. 2
D. -1
Answer: C. 2
Explanation
Explanation:
In Python’s file handling, theseek(offset, reference_point)method repositions the file pointer within a file. Thereference_point(also calledwhence) specifies from where the offset is measured:
Reference Point Value Meaning 0Beginning of file Absolute positioning 1Current position Relative to current pointer 2End of file Relative to the end of the file When we use:
fileObject.seek(offset, 2)the file pointer moves
offsetbytes relative to the end of the file.
- If the
offsetis 0, the pointer is positioned at EOF (End of File).- If the
offsetis negative, the pointer moves backward from the end.- Positive offsets (beyond EOF) are technically allowed but rarely used because they point past the file’s actual end.
Example:
f = open("data.txt", "rb") f.seek(0, 2) # move pointer to the end of file position = f.tell() print(position)This will display the total number of bytes in the file, as the pointer is now at its end.
As per the Python official documentation,
“The whence argument can be 0 (absolute positioning), 1 (relative to current position), or 2 (relative to the file’s end).”Thus, when
reference_pointis 2, movement occurs relative to the end of the file.
132. Does seek() work the same for text and binary files?
A. Yes
B. No
C. Only in read mode
D. Only in write mode
Answer: B. No
Explanation
Explanation:
Theseek()method is used to reposition the file pointer to a specific location within a file.
However, its behavior is not identical for text files and binary files.In binary files (opened with mode
'rb'or'wb'), data is handled as raw bytes, so every movement withseek(offset, reference_point)corresponds exactly to that number of bytes.
Example:f = open("data.bin", "rb") f.seek(10, 0) # moves pointer to 10th byteHere, movement is precise and reliable because no encoding or newline conversion is involved.
In text files (opened with mode
'r'or'w'), data is processed through encodings (like UTF-8) and newline conversions (\n↔\r\non Windows).
These conversions make byte-level positioning inaccurate — meaningseek()might not move exactly where you expect, especially when using offsets other than zero.Therefore,
seek()works reliably and accurately only in binary mode, while in text mode it can behave differently depending on the system’s encoding and newline conventions.As per the Python official documentation,
“In text files, only offsets returned by tell() are legal arguments to seek(). The whence value should be 0.”Hence,
seek()does not work exactly the same way in text and binary files.
133. What is the output of the following code?
f = open("testfile.txt", "r")
print(f.tell())
f.read(5)
print(f.tell())
f.close()
If the file contains "Hello Python", what will be the output?
A. 0 5
B. 0 11
C. 5 10
D. 1 6
Answer: A. 0 5
Explanation
Explanation:
- When a file is opened, the file pointer is positioned at the beginning of the file.
Hence,f.tell()returns 0 initially.- The
read(5)method reads the first 5 characters of the file ("Hello").- After reading, the pointer moves 5 positions forward.
Therefore, the secondf.tell()returns 5.So the program prints:
0 5This shows how the
tell()method tracks the current position of the file pointer, and how reading changes it accordingly.
134. Which method would you use to read a file randomly instead of sequentially?
A. read()
B. readline()
C. seek()
D. write()
Answer: C. seek()
Explanation
Explanation:
Normally, when we read a file usingread()orreadline(), data is accessed sequentially — from start to end in order.
However, sometimes we need to jump to a specific part of the file to read or modify data. This is called random access.The
seek(offset, reference_point)method is used for this purpose.
It moves the file pointer to any desired position in the file, enabling reading or writing from that point onward.“The seek() function is used to reposition the file pointer for random file access.”
“Change the stream position to the given byte offset.”For example:
f = open("data.txt", "rb") f.seek(10) # Moves pointer to 10th byte print(f.read(5)) # Reads 5 bytes from there f.close()Thus,
seek()allows non-sequential (random) access, while methods likeread()orreadline()only read sequentially.
135. If seek(0,2) is executed on a file, what does it do?
A. Moves pointer to start
B. Moves pointer to current position
C. Moves pointer to end
D. Moves pointer to 2nd byte
Answer: C. Moves pointer to end
Explanation
Explanation:
Theseek(offset, reference_point)method repositions the file pointer to a specific byte location in the file.
Here, theoffsetis0and thereference_point(also calledwhence) is2.In Python:
0→ Beginning of file1→ Current position2→ End of fileSo,
seek(0, 2)moves the file pointer to the end of the file, because it sets the pointer0 bytes away from the end.
This is often used when you want to append data or check the total size of a file usingtell().“The seek() function is used to reposition the file pointer for random file access.”
“Change the stream position to the given byte offset.”Example:
f = open("data.txt", "rb") f.seek(0, 2) # Moves pointer to end of file print(f.tell()) # Shows total number of bytes f.close()Thus, executing
seek(0,2)places the file pointer exactly at the end of the file, without moving it forward or backward.
136. Why do we need tell() method?
A. To know file size
B. To know current position of file pointer
C. To write data at beginning
D. To close the file
Answer: B. To know current position of file pointer
Explanation
Explanation:
In Python file handling, thetell()method is used to find the current position of the file pointer — i.e., how many bytes have been read or written from the beginning of the file.
It returns an integer value representing the byte offset of the file pointer.This information helps the program determine where the next read or write operation will take place.
tell()is especially useful when working with large files or when combined withseek()for random access.“The tell() method returns the current position of the file pointer in terms of bytes from the beginning of the file.”
“Return the current stream position.”Example:
f = open("example.txt", "r") print(f.tell()) # 0 at the beginning f.read(10) print(f.tell()) # 10 after reading 10 bytes f.close()Thus,
tell()allows the programmer to track the exact position of the file pointer during file operations.
137. What will happen if you execute seek(-3,1)?
A. Moves pointer 3 bytes back from current position
B. Moves pointer to beginning
C. Moves pointer 3 bytes forward from end
D. Raises error
Answer: A. Moves pointer 3 bytes back from current position
Explanation
Explanation:
Theseek(offset, reference_point)function is used to reposition the file pointer.
Here,
offset = -3(negative value) → moves the pointer backward by 3 bytesreference_point = 1→ represents current positionSo,
seek(-3, 1)moves the file pointer 3 bytes backward from its current position.
This is useful for re-reading or rewriting data without reopening the file.However, note that negative offsets are not allowed in text mode, because of character encoding differences.
They work properly only in binary mode (‘rb’ or ‘rb+’).“The seek() function is used to reposition the file pointer for random file access.”
“Change the stream position to the given byte offset.”f = open("data.txt", "rb") f.read(10) # pointer moves to byte 10 f.seek(-3, 1) # moves back to byte 7 print(f.tell()) # shows 7 f.close()Thus, executing
seek(-3, 1)repositions the pointer 3 bytes backward from the current location, when used in binary mode.
138. Consider binary files. Why is seek() preferred over reading sequentially?
A. Faster access to specific data
B. Required for all reads
C. Writes data automatically
D. Deletes bytes automatically
Answer: A. Faster access to specific data
Explanation
Explanation:
In binary files, data is often stored as records or fixed-size blocks.
Reading such files sequentially means starting from the beginning and moving step by step until the desired data is reached — which can be slow and inefficient, especially for large files.The
seek()method allows direct or random access to any specific byte or record in the file without reading all preceding data.
This makesseek()much faster and more efficient than sequential reading when only a particular section of the file is needed.“The seek() function is used to reposition the file pointer for random file access.”
“Change the stream position to the given byte offset.”Example:
f = open("records.dat", "rb") f.seek(200) # Move pointer directly to byte 200 record = f.read(50) # Read only the desired record f.close()Thus,
seek()is preferred for binary files because it allows faster and targeted data access without processing the entire file sequentially.
139. Which of the following is true about seek() and tell()?
A. seek() returns current position
B. tell() moves pointer
C. seek() moves pointer, tell() returns pointer position
D. Both write data
Answer: C. seek() moves pointer, tell() returns pointer position
Explanation
Explanation:
The two most important file-pointer-related methods in Python areseek()andtell(), and they serve complementary purposes:
seek(offset, reference_point)→ moves the file pointer to a specific location (used for random access).tell()→ returns the current position of the file pointer (used to know where reading/writing will occur next).Together, they help in controlling and tracking file reading/writing operations efficiently — especially in binary files or large text files.
“The seek() function is used to reposition the file pointer for random file access.”
“The tell() method returns the current position of the file pointer in terms of bytes from the beginning of the file.”
“Change the stream position to the given byte offset.”
“Return the current stream position.”Example:
f = open("demo.txt", "rb") f.seek(10) # Moves file pointer to byte 10 print(f.tell()) # Prints: 10 f.close()Thus,
seek()→ controls where the file pointer goestell()→ informs where the file pointer currently isThey are often used together for precise file handling operations.
140. What is the main limitation of using seek() in text files?
A. Cannot read content
B. Byte positions may not match character positions due to encoding
C. Cannot write data
D. Only works in append mode
Answer: B. Byte positions may not match character positions due to encoding
Explanation
Explanation:
In text files, data is stored using character encoding such as UTF-8, UTF-16, etc.
These encodings may use multiple bytes to represent a single character (for example, some Unicode characters use 2 or 3 bytes).The
seek()method, however, always moves the file pointer by bytes, not by characters.
As a result, when you useseek()in text mode, the byte positions may not align with character positions, leading to inaccurate pointer placement or even decoding errors.That’s why
seek()works more predictably in binary mode ('rb'or'rb+'), where data is handled as raw bytes rather than encoded characters.“The seek() function is used to reposition the file pointer for random file access.”
“In text files, using seek() may not give exact results because of variable-length encodings.”
“In text files (those opened without a ‘b’), only offsets returned by tell() are legal arguments to seek().”Example:
f = open("sample.txt", "r", encoding="utf-8") f.seek(5) # Moves 5 bytes ahead (may be mid-character in UTF-8) print(f.readline()) f.close()In the above case, the pointer might land in the middle of a multi-byte character, causing decoding issues or incorrect reading.
Thus,
seek()in text files has the limitation that byte offsets may not accurately represent character positions, making it unreliable for random access.
141. What does the following statement do?
fileobject = open("testfile.txt","r+")A. Opens the file for reading only
B. Opens the file for reading and writing
C. Opens the file in append mode
D. Opens the file as a binary file
Answer: B. Opens the file for reading and writing
Explanation
Explanation:
In Python, theopen()function is used to open a file and returns a file object.
The second argument of theopen()function specifies the mode — that is, how the file should be opened (read, write, append, etc.).The mode
"r+"means:
- Open the file for both reading and writing.
- The file must already exist — if it does not, Python raises a
FileNotFoundError.- The file pointer is placed at the beginning of the file.
- Existing content can be read, overwritten, or modified.
“The open() function is used to open a file in different modes like read, write, and append.”
“Mode ‘r+’ opens the file for both reading and writing. The file pointer is placed at the beginning of the file.”
“Open file and return a corresponding file object. The mode ‘r+’ opens the file for both reading and writing.”Example:
f = open("testfile.txt", "r+") content = f.read(5) # Reads first 5 characters f.write("New") # Overwrites next characters f.close()Thus,
"r+"mode is used when you want to read and modify an existing file without creating a new one.
142. In Program 2-2, what does fileobject.tell() return initially?
A. 10
B. 0
C. Length of file
D. -1
Answer: B. 0
Explanation
Explanation:
Thetell()method in Python’s file handling returns the current position of the file pointer (also called the file cursor).When a file is opened (using
open()), the file pointer is automatically positioned at the beginning of the file.
Therefore, before any read or write operation, the pointer position is 0 — the first byte of the file.So,
fileobject.tell()initially returns 0 because the file pointer hasn’t moved yet.
Example:
f = open("sample.txt", "r") print(f.tell()) # Output → 0 data = f.read(5) print(f.tell()) # Output → 5 (moved 5 bytes forward) f.close()
- The first
tell()returns 0 (file pointer at start).- The second
tell()returns 5, showing the pointer moved 5 characters ahead after reading.Concept Summary:
Method Purpose Initial Value tell()Returns current file pointer position (in bytes) 0at file startseek(offset)Moves the file pointer to a specific position Can be used with tell()“The tell() function gives the current position of the file pointer.”
“Initially, when a file is opened, the file pointer is at the beginning (position 0).”
tell()returns an integer giving the file object’s current position in the stream.
143. What will fileobject.seek(0) do?
A. Move pointer to 0th byte from beginning
B. Move pointer 0 bytes forward from current position
C. Move pointer to end of file
D. Overwrite first byte
Answer: A. Move pointer to 0th byte from beginning
Explanation
Explanation:
Theseek()method is used to reposition the file pointer within a file.
It takes two parameters:seek(offset, reference_point)
- offset → number of bytes to move
- reference_point → starting position (default is
0, i.e., beginning of file)So,
fileobject.seek(0)is equivalent to
fileobject.seek(0, 0)This command moves the file pointer to the 0th byte from the beginning of the file, meaning it resets the file pointer back to the start.
Example:
f = open("example.txt", "r") f.read(10) # Move pointer 10 bytes forward print(f.tell()) # Output: 10 f.seek(0) # Move pointer back to beginning print(f.tell()) # Output: 0 f.close()🔹 After reading 10 bytes, pointer is at position 10.
🔹 Afterseek(0), pointer goes back to the beginning (0th byte).Concept Summary:
Method Action Description seek(offset)Moves pointer Moves pointer to given byte position seek(0)Reset pointer Moves pointer to start of file tell()Returns pointer Shows current byte position “The seek() function is used to reposition the file pointer for random file access.”
“seek(0) sets the file pointer at the beginning of the file.”seek(offset, whence=0)changes the stream position to the given byte offset.
144. In Program 2-2, after fileobject.seek(10), what does fileobject.read() do?
A. Reads first 10 bytes
B. Reads all bytes starting from 10th byte
C. Reads last 10 bytes
D. Reads the whole file again
Answer: B. Reads all bytes starting from 10th byte
Explanation
Explanation:
Theseek()method repositions the file pointer to a specific byte location within the file.
When you executefileobject.seek(10)it moves the file pointer to the 10th byte from the beginning of the file (since the default reference point is
0, i.e., the start of the file).After this, when you call
fileobject.read()it reads from the current pointer position (10th byte) up to the end of the file (EOF).
Thus, it skips the first 10 bytes and returns the remaining content from that position onward.
Example:
f = open("sample.txt", "r") f.seek(10) # Move pointer to 10th byte data = f.read() # Read from 10th byte to EOF print(data) f.close()🔹 If
sample.txtcontains"Hello Python Programming",
thenf.read()will return “n Programming” after moving to the 10th byte.Concept Summary:
Function Purpose Behavior seek(offset)Move pointer Moves pointer to specified byte (default from start) read()Read content Reads from current pointer to end of file tell()Get pointer Returns current pointer position “The seek() function repositions the file pointer. After seek(), reading begins from the new position.”
145. What is the output of fileobject.tell() after fileobject.seek(10)?
A. 0
B. 10
C. 5
D. Length of file
Answer: B. 10
Explanation
Explanation:
Theseek(offset)method repositions the file pointer to a specific byte within the file.
When you execute:fileobject.seek(10)the file pointer moves 10 bytes from the beginning (since the default reference point,
whence, is0— start of the file).Then,
fileobject.tell()returns the current byte position of the file pointer, which in this case is 10.
Thus,
tell()confirms that the file pointer is now at byte position 10 — meaning the next read or write operation will begin from this position.Example:
f = open("example.txt", "r") f.seek(10) print(f.tell()) f.close()Output:
10This verifies that the pointer successfully moved to the 10th byte of the file.
Concept Summary:
Method Purpose Example Output seek(offset)Move pointer to given byte f.seek(10)Moves to 10th byte tell()Return current pointer position f.tell()10“The tell() method returns the current file pointer position. seek() can be used to move the pointer to a specific byte location.”
146. Which mode should be used to create a new file and overwrite existing contents?
A. 'r'
B. 'w'
C. 'a'
D. 'r+'
Answer: B. 'w'
Explanation
Explanation:
The'w'mode stands for write mode in Python file handling.When a file is opened in
'w'mode:
- If the file does not exist, Python automatically creates a new file.
- If the file already exists, Python erases all its existing content before writing new data.
- The file pointer is placed at the beginning of the file, ready for writing.
Thus,
'w'mode is used whenever you want to create a new file or completely overwrite an existing one.Example:
f = open("demo.txt", "w") f.write("Hello World!") f.close()If the file
demo.txtalready had some text, it will be deleted, and only"Hello World!"will remain inside the file.Concept Summary:
Mode Description Creates new file if missing Overwrites existing content 'r'Opens file for reading only No No 'w'Opens file for writing Yes Yes 'a'Opens file for appending Yes No 'r+'Opens file for both reading and writing No No (unless overwritten manually)
147. Which mode should be used to add data at the end of an existing file without deleting previous content?
A. 'w'
B. 'r+'
C. 'a'
D. 'rb'
Answer: C. 'a'
Explanation
Explanation:
The'a'mode stands for append mode in Python file handling.When a file is opened in
'a'mode:
- Data is added at the end of the file, not at the beginning.
- The existing content remains unchanged.
- If the specified file does not exist, Python creates a new file automatically.
- The file pointer is positioned at the end of the file before every write operation.
Thus,
'a'mode is ideal when you want to add new data without erasing what is already present.Example:
f = open("notes.txt", "a") f.write("\nThis line will be added at the end.") f.close()If the file
notes.txtalready contains some text, this new line will be added to the end of the file without removing any existing content.Concept Summary:
Mode Description Creates new file if missing Deletes existing content Adds data to end 'r'Read only No No No 'w'Write (overwrite) Yes Yes No 'a'Append (write at end) Yes No Yes 'r+'Read and write No No No (unless overwritten manually) “When a file is opened using mode 'a', new data is appended at the end of the file. The previous contents remain intact.”'a'— Open for writing, appending to the end of the file if it exists.
148. What is the main difference between write and append modes?
A. Write mode reads the file, append mode does not
B. Write mode overwrites file, append mode preserves existing data
C. Append mode deletes file
D. Both behave the same
Answer: B. Write mode overwrites file, append mode preserves existing data
Explanation
Explanation:
Both'w'(write) and'a'(append) modes are used for writing data into a text file, but their behavior differs significantly:
- Write Mode
'w'
- Opens the file for writing.
- Deletes (overwrites) all existing content in the file before writing new data.
- If the file does not exist, a new file is created.
- The file pointer is placed at the beginning of the file.
- Append Mode
'a'
- Opens the file for writing as well, but preserves existing content.
- New data is added at the end of the file (after the existing content).
- If the file does not exist, a new file is created.
- The file pointer is placed at the end of the file before each write operation.
Thus, the main difference is that
'w'overwrites the file, whereas'a'adds new data after the existing content.Example:
# Using 'w' mode f = open("example.txt", "w") f.write("First Line") f.close() # Using 'a' mode f = open("example.txt", "a") f.write("\nSecond Line") f.close()After running this code,
the fileexample.txtwill contain:First Line Second Linebecause
'a'added text at the end without removing the previous line.Concept Summary:
Mode Behavior Effect on Existing Data Pointer Position 'w'Write mode Deletes previous content Beginning 'a'Append mode Keeps previous content, adds new data at end End “In write mode, previous contents of the file are erased. In append mode, new data is added at the end without deleting existing data.”'w'– Open for writing, truncating the file first.'a'– Open for writing, appending to the end of the file if it exists.
149. In file traversal, which Python construct is commonly used to read a file line by line?
A. while with read()
B. for loop on file object
C. readlines() without loop
D. write()
Answer: B. for loop on file object
Explanation
Explanation:
In Python, the most efficient and memory-friendly way to read a text file line by line is by using aforloop directly on the file object.When a file is opened in read mode and used in a
forloop, Python automatically reads one line at a time until the end of the file (EOF) is reached.
This avoids loading the entire file into memory, making it ideal for large files.For example:
f = open("data.txt", "r") for line in f: print(line.strip()) f.close()Here,
- Each iteration of the loop fetches one line from the file.
- The loop automatically stops when there are no more lines to read.
- This approach is both simple and efficient compared to methods like
read()orreadlines()that load the whole file content at once.Concept Summary:
Method Description Memory Usage Efficiency read()Reads entire file as one string High Low for large files readlines()Reads all lines into a list High Moderate for line in fileobject:Reads one line at a time Low High (recommended) Example Output:
If
data.txtcontains:Hello Python File HandlingOutput of the above code will be:
Hello Python File Handling“The file object can be iterated using a for loop, which reads one line at a time efficiently.”
“Iterating over a file object yields each line in the file.”
150. After creating a file with open("practice.txt","w"), what will happen if write() is not called?
A. File remains empty
B. File is deleted
C. Python raises error
D. File contains default text
Answer: A. File remains empty
Explanation
Explanation:
When a file is opened usingopen("practice.txt", "w")Python performs the following actions:
- It creates a new empty file named
practice.txtif it does not already exist.- If the file already exists, Python erases its previous content (truncates it to zero length).
- The file pointer is placed at the beginning of the file, ready for writing.
However, no data is written automatically.
If you do not call thewrite()orwritelines()method, the file will remain completely empty even after it is closed.This behavior shows that opening a file in
'w'mode prepares it for writing but does not add any content by itself.Example:
f = open("practice.txt", "w") f.close()After running this code:
- A new file named
practice.txtwill be created in the working directory.- The file will be empty because no data was written using
write().Concept Summary:
Mode Description Automatically writes content Result if write() not called 'w'Opens file for writing (overwrites existing content) No File remains empty 'a'Opens file for appending No File remains unchanged (if no write) 'r'Opens file for reading Not applicable Error if file doesn’t exist “Opening a file in write mode creates a new empty file if it does not exist. Content is added only when write() or writelines() is executed.”
w' — Open for writing, truncating the file first.
151. Which of the following is TRUE about ‘r+‘ mode?
A. Creates new file if it doesn’t exist
B. Pointer starts at end of file
C. Allows both reading and writing, file must exist
D. Always overwrites file
Answer: C. Allows both reading and writing, file must exist
Explanation
Explanation:
The'r+'mode in Python opens an existing file for both reading and writing. However, the file must already exist — if it does not, Python raises aFileNotFoundError.
When opened, the file pointer is positioned at the beginning of the file, allowing data to be read or overwritten from the start. Unlike'w'mode, it does not truncate the file; existing content remains unless you explicitly overwrite it.Example:
f = open("data.txt", "r+") print(f.read()) # Reads file content f.seek(0) f.write("Python") # Overwrites from the start f.close()
152. What does fileobject.read() return after seek() moves pointer to a specific position?
A. Entire file content
B. Content starting from pointer position to EOF
C. Only the byte at pointer
D. Nothing
Answer: B. Content starting from pointer position to EOF
Explanation
Explanation:
Whenseek()is used, it repositions the file pointer to a specific byte location within the file.
After that, callingread()starts reading from the current pointer position (set byseek()) up to the end of the file (EOF), unless a size argument is provided.
This enables random file access, allowing the program to read only the desired portion of the file without rereading the entire content.Example:
f = open("example.txt", "r") f.seek(6) # Moves pointer to 6th byte print(f.read()) # Reads content from 6th byte to EOF f.close()If the file contains
"Hello Python", the output will be"Python".
153. Which of the following sequences correctly represents Program 2-2 execution?
A. Open file → read → tell → seek → read → close
B. Open file → write → seek → read → close
C. Open file → append → tell → write → close
D. Open file → readlines → split → close
Answer: A. Open file → read → tell → seek → read → close
Explanation
Explanation:
In Program 2-2 (NCERT Class 12, File Handling), the file is opened in read mode ("r"). The program first reads the file to display initial contents, then usestell()to determine the current file pointer position.
Next, it usesseek()to move the pointer to a specific byte location and again callsread()to display the remaining content from that position. Finally, the file is closed usingclose().This demonstrates how
tell()andseek()are used together for file navigation and random access.Example Flow (Simplified):
file = open("test.txt", "r") print(file.read()) # Read initial content print(file.tell()) # Get current pointer position file.seek(10) # Move pointer to 10th byte print(file.read()) # Read from byte 10 to EOF file.close()
154. What happens if you use seek(10) on a file with less than 10 bytes?
A. Raises error
B. Pointer moves to EOF
C. Overwrites file
D. File is deleted
Answer: B. Pointer moves to EOF
Explanation
Explanation:
When you call the methodseek(10)in Python, it tries to move the file pointer (the internal marker that tracks where the next read or write will occur) 10 bytes from the beginning of the file.
The second argument (called reference point or whence) by default is0, meaning that the position is counted from the start of the file.Now, if the file has less than 10 bytes (for example, only 6 bytes long), Python does not raise an error. Instead, it quietly moves the file pointer to the end of the file (EOF).
At this point, the pointer position equals the file’s size (for example, position 6 for a 6-byte file).Any attempt to read() after this will simply return an empty string (”), because the pointer is already at or beyond the file’s end — there is no content left to read.
This is a key difference between file pointers and list indices: going beyond the file’s length doesn’t cause an IndexError or IOError.Example:
# demo.txt contains: "Hello" f = open("demo.txt", "r") # File has 5 bytes f.seek(10) # Move pointer to 10th byte (beyond EOF) print(f.tell()) # Output: 10 (pointer is now at EOF) print(f.read()) # Output: '' (empty string) f.close()Even though the file only contains 5 bytes, Python sets the pointer at position 10 (EOF).
Reading from this position returns an empty string since there’s no data beyond the end of the file.Conceptual Note:
- The
seek()method only moves the file pointer; it doesn’t modify file data.- Moving beyond EOF is allowed in Python — especially useful when writing, as new data can be added from that position if the file is opened in write or append mode.
- In text mode, this is byte-based and may not correspond exactly to characters due to encodings like UTF-8.
155. Why is it important to close a file after seek and read operations?
A. To reset pointer
B. To flush buffer and release system resources
C. To delete file
D. To move pointer automatically
Answer: B. To flush buffer and release system resources
Explanation
Explanation:
Theclose()method is one of the most important steps in Python file handling.
After performing file operations such as read(), write(), or seek(), the file remains open and occupies system resources like memory and file descriptors.Calling
close()performs two critical functions:
- Flushes the Buffer:
If the file was opened in write or update mode, Python may temporarily store (buffer) data in memory before actually writing it to disk.
When you callclose(), this buffer is flushed, meaning all pending data is written permanently to the file.
This ensures data integrity — no information is lost due to unflushed buffers.- Releases System Resources:
Every open file consumes system-level resources.close()releases these resources back to the operating system, making them available for other programs.
Not closing files may lead to memory leaks or “too many open files” errors in large programs.After
close()is called, any attempt to perform operations likeread(),write(), orseek()on the same file object will raise a ValueError, indicating the file is closed.Example:
f = open("demo.txt", "r") content = f.read() # Read operation f.seek(0) # Move pointer back to start f.close() # Properly close the file print(f.closed) # Output: TrueIf you forget to call
close(), Python’s garbage collector may close the file automatically at program exit — but relying on this is not recommended, as the timing is unpredictable.Conceptual Note:
Instead of manually closing files, it’s safer to use the with statement, which automatically handles closure even if an error occurs:
with open("demo.txt", "r") as f: data = f.read() # File automatically closed here
156. What does open("practice.txt", "w+") do?
A. Opens the file for reading only
B. Opens the file for reading and writing; overwrites if file exists
C. Opens file in append mode
D. Opens file as binary
Answer: B. Opens the file for reading and writing; overwrites if file exists
Explanation
Explanation:
Theopen()function in Python accepts two arguments — the file name and the mode.
Here, the mode used is"w+", which combines the behavior of'w'(write mode) and'r+'(read/write mode).When you open a file with
"w+":
- Read and Write Access:
The file is opened for both reading and writing operations.
You can use methods likeread(),write(), orseek()on the same file object.- Overwrites Existing Content:
If the file already exists, its previous content is deleted immediately when opened in"w+"mode.
The file pointer is positioned at the beginning (byte 0), and any new write operation starts from there.- Creates a New File if Missing:
If"practice.txt"does not exist, Python automatically creates a new empty file before opening it.This makes
"w+"useful when you need to perform both reading and writing, but don’t need to preserve old data.Example:
# Example 1: File exists f = open("practice.txt", "w+") f.write("Python File Handling") f.seek(0) # Move pointer to start print(f.read()) # Output: Python File Handling f.close() # Example 2: File doesn't exist # Python creates a new file automaticallyIn both cases,
"w+"ensures the file is accessible for both reading and writing — but note that existing data is lost if the file previously existed.Conceptual Note:
"w+"→ Read + Write; overwrites existing data"r+"→ Read + Write; requires existing file"a+"→ Read + Write; appends data without deleting old contentThus, choosing the right mode is crucial to prevent accidental data loss.
“The mode argument determines how the file is opened. ‘w+’ opens the file for both writing and reading. The file is truncated to zero length if it exists.”
157. What happens if a file is opened in 'a' mode and new data is written?
A. Previous data is deleted
B. New data is written after existing content
C. File is read-only
D. Error occurs
Answer: B. New data is written after existing content
Explanation
Explanation:
When a file is opened in append mode ('a'), Python prepares the file only for writing, and any new content is added to the end of the file instead of deleting or replacing existing data.Here’s what actually happens step-by-step:
- Preserves Existing Data:
The original content in the file remains unchanged. Nothing is deleted or truncated.- Moves Pointer to End:
The file pointer automatically moves to the end of the file, regardless of any previous data length.
So, any newwrite()orwritelines()operation begins after the last existing character.- Creates File if Missing:
If the file does not exist, it is created automatically before writing begins.- Cannot Read:
The'a'mode allows only writing. If you try toread()in this mode, Python will raise an error.
To read and append together, use'a+'.Example:
# Example file operation in append mode f = open("example.txt", "a") f.write("\nThis line is newly appended.") f.close()If
example.txtalready contains:Python is fun.After executing the code, it becomes:
Python is fun. This line is newly appended.Conceptual Note:
Mode Description Effect on Old Data 'w'Write only Deletes old content 'a'Append only Keeps old content, adds new at end 'w+'Read + Write Deletes old content 'a+'Read + Append Keeps old content, allows read/write So
'a'mode is safe for adding data without losing what’s already in the file.“‘a’ opens the file for writing, appending to the end of the file if it exists.”
158. In Program 2-3, which loop allows the user to enter multiple lines interactively?
A. for loop
B. while loop
C. do-while loop
D. None
Answer: B. while loop
Explanation
Explanation:
In Program 2-3 (as given in NCERT Class 12 Computer Science), the user is allowed to enter multiple lines of text that are written to a file.
This is implemented using awhile True:loop — the most common Python construct for repeated input until the user chooses to stop.Program 2-3 (NCERT Example)
# Program 2-3: Writing multiple lines into a file f = open("practice.txt", "w") while True: line = input("Enter a line: ") f.write(line + "\n") ans = input("Want to enter more lines? (y/n): ") if ans == 'n': break f.close()Step-by-Step Logic:
while True:
Creates an infinite loop that keeps taking user input continuously.input()
Accepts each line from the user.f.write(line + "\n")
Writes that line into the file, adding a newline character.- Break Condition:
If the user types'n', the statementbreakexits the loop immediately.Thus, the loop continues until the user decides to stop — a classic interactive input pattern.
Why Not Other Options?
Option Reason Incorrect A. for loop Used when the number of iterations is known. Here, it’s unknown (depends on user). C. do-while loop Python has no do-whileconstruct.D. None Not applicable; whileclearly handles repetition here.Key Concept:
The
while True:loop withbreakprovides interactive and indefinite repetition, ideal for reading or writing multiple lines of user data.
159. In Program 2-3, what happens if the user enters 'n' when asked “Do you wish to enter more data?”
A. Next line is overwritten
B. Loop breaks and file is closed
C. File is deleted
D. Error occurs
Answer: B. Loop breaks and file is closed
Explanation
Explanation:
In Program 2-3, awhile True:loop is used to repeatedly take user input and write it into a file.
At the end of each iteration, the program asks the user whether they want to continue adding more data.f = open("practice.txt", "w") while True: line = input("Enter a line: ") f.write(line + "\n") ans = input("Do you wish to enter more data? (y/n): ") if ans == 'n': break f.close()What Happens When User Enters ‘n’:
- The condition
if ans == 'n':becomes True.- The statement
breakexecutes, which immediately exits thewhileloop.- The next statement
f.close()runs, which:
- Saves all buffered data to the file, and
- Closes the file properly to prevent data loss or file corruption.
Why Not Other Options?
Option Reason Incorrect A. Next line is overwritten No overwriting occurs; file writing stops safely. C. File is deleted No file deletion command is used. D. Error occurs No error — breakis a valid and controlled exit from the loop.Key Concept:
- The
breakstatement terminates a loop instantly.- The
close()method ensures all written data is flushed (saved) to the file and system resources are released.
160. Which mode should be used to read a file line by line?
A. 'w'
B. 'r'
C. 'a'
D. 'w+'
Answer: B. 'r'
Explanation
Explanation:
When you want to read a file line by line, you should open it in read mode (‘r’).
This mode allows you to only read the file’s contents — no writing or modification is permitted.Example:
f = open("data.txt", "r") for line in f: print(line.strip()) f.close()How It Works:
open("data.txt", "r")
Opens the file in read-only mode. The file must exist; otherwise, Python raises aFileNotFoundError.for line in f:
Iterates line by line, automatically handling large files efficiently without loading the entire file into memory.line.strip()
Removes extra newline characters (\n) at the end of each line.f.close()
Ensures the file is closed properly after reading.Why Not Other Modes?
Mode Description Why Not Suitable ‘w’ Write mode Erases existing file before writing ‘a’ Append mode Adds new data; cannot read existing content ‘w+’ Read/write mode Overwrites existing file when opened Key Concept:
- The
'r'mode is safe and non-destructive — it doesn’t modify or delete any data.- When reading large files, line-by-line traversal using a
forloop is the most efficient approach.
161. In Program 2-4, which method is used to read a single line from the file?
A. read()
B. readline()
C. readlines()
D. write()
Answer: B. readline()
Explanation
Explanation:
Thereadline()method is used to read one line at a time from a text file.
When called repeatedly, it reads subsequent lines until the end of the file (EOF).Example:
f = open("sample.txt", "r") line = f.readline() print(line) f.close()If the file contains:
Hello Python Welcome to file handlingThen after the first
readline(), output will be:Hello PythonHow It Works:
readline()reads characters from the current file pointer position up to the next newline character (\n), including it.- Each call to
readline()moves the pointer to the start of the next line.- When the end of the file is reached, it returns an empty string (”).
Comparison with Other Methods:
Method Description Usage read()Reads the entire file content as one string Useful for small files readline()Reads one line at a time Ideal for sequential line reading readlines()Reads all lines at once and returns a list Useful when you need all lines in memory write()Writes data to a file Used in write/append modes only Key Concept:
readline()is memory-efficient and commonly used in loops for line-by-line processing:f = open("data.txt", "r")
while True:
line = f.readline()
if not line:
break
print(line.strip())
f.close()
162. What is the termination condition for the while loop in Program 2-4?
A. EOF reached (readline() returns empty string)
B. User input 'n'
C. File pointer at 0
D. None
Answer: A. EOF reached (readline() returns empty string)
Explanation
Explanation:
In Program 2-4, the file is read line by line using thereadline()method inside awhileloop.
The loop continues untilreadline()returns an empty string (”), which indicates that the end of file (EOF) has been reached.Example (as shown in NCERT Program 2-4):
f = open("practice.txt", "r") str = f.readline() while str: print(str) str = f.readline() f.close()Step-by-Step Execution:
- The first call to
readline()reads the first line and assigns it tostr.- The condition
while str:checks if the string is non-empty.- As long as
readline()returns a non-empty string, the loop executes.- When the end of file is reached,
readline()returns an empty string (”).- Since an empty string evaluates to False, the loop terminates.
Key Concept:
- EOF (End of File) acts as the natural termination point for file-reading loops.
- The
whileconditionwhile str:automatically stops when there’s no more data to read.Illustration:
If the file
practice.txtcontains:Python File Handling ExampleThen during loop execution:
Iteration 1: str = "Python\n" Iteration 2: str = "File Handling\n" Iteration 3: str = "Example" Iteration 4: str = "" ← EOF reached → loop stopsImportant Note:
- The condition
while str:works because empty strings evaluate to False in Python.- This technique ensures safe reading of unknown-length files.
163. What happens if you use readlines() instead of readline() in Program 2-4?
A. Reads one line at a time
B. Reads all lines into a list
C. Overwrites file
D. Deletes EOF
Answer: B. Reads all lines into a list
Explanation
Explanation:
In Program 2-4, if you replacereadline()withreadlines(), the program’s behavior changes significantly.
Instead of reading one line at a time, thereadlines()method reads the entire file at once and stores all lines as elements of a list.Example:
f = open("practice.txt", "r") lines = f.readlines() print(lines) f.close()If the file
practice.txtcontains:Python File Handling ExampleThen the output will be:
['Python\n', 'File Handling\n', 'Example']How It Works:
readline()→ Reads only one line from the file.readlines()→ Reads all lines from the file and returns a list of strings.- Each string in the list represents one line and usually ends with a newline character (
\n).Why It Matters in Program 2-4:
In the original
whileloop version:str = f.readline() while str: print(str) str = f.readline()Each iteration reads one line until EOF.
If you replace it withreadlines(), then it would read the entire file in one go, eliminating the need for the loop.Thus:
readline()→ Used for sequential, line-by-line processing (memory efficient).readlines()→ Suitable when the entire file needs to be processed at once (less efficient for large files).Key Concept:
Method Description Return Type readline()Reads a single line String readlines()Reads all lines List of strings read()Reads entire file content Single string
164. Which of the following is TRUE about ‘w+‘ and ‘a+‘ modes?
A. w+ appends, a+ overwrites
B. w+ overwrites, a+ appends
C. Both append
D. Both overwrite
Answer: B. w+ overwrites, a+ appends
Explanation
Explanation:
The modesw+anda+both open files for reading and writing, but they differ in how they handle existing content and pointer position.1. ‘w+’ Mode (Write + Read Mode)
- Opens the file for both reading and writing.
- If the file exists, it is completely cleared (overwritten).
- If the file does not exist, it is created automatically.
- The file pointer starts at the beginning of the file.
Example:
f = open("sample.txt", "w+") f.write("Hello") f.seek(0) print(f.read()) # Output: HelloIf “sample.txt” had previous data, it will be erased when opened in
'w+'.2. ‘a+’ Mode (Append + Read Mode)
- Opens the file for both reading and writing.
- If the file exists, the existing data is not deleted.
- New data is added at the end of the file.
- If the file doesn’t exist, it is created automatically.
- The file pointer starts at the end, so to read old data, you must use
seek(0)first.Example:
f = open("sample.txt", "a+") f.write("World") f.seek(0) print(f.read()) # Reads entire file contentKey Difference Between ‘w+’ and ‘a+’:
Feature w+Modea+ModeFile existence Creates new or overwrites existing Creates new if not exists File pointer position Starts at beginning Starts at end Data handling Deletes previous data Preserves previous data Purpose Rewriting file Adding more data Key Concept:
'w+'is destructive — erases old data.'a+'is non-destructive — appends new data after EOF.- Both support reading and writing, but pointer behavior differs.
165. What will happen if fileobject.close() is not called after writing?
A. Data may not be saved to disk
B. File is deleted automatically
C. File pointer resets to 0
D. Nothing happens
Answer: A. Data may not be saved to disk
Explanation
Explanation:
When a file is opened for writing in Python, data is first stored temporarily in a buffer (RAM). The data is actually written to disk only when:
- The buffer is full,
- The program exits normally, or
- The
close()method (orwithstatement) is used to flush and close the file.If you forget to call
fileobject.close(), some or all written data may remain in the buffer and not get saved permanently. Additionally, system resources like file handles remain occupied until garbage collection occurs.
166. In Program 2-3, which statement ensures user input is written to the file?
A. data = input(...)
B. fileobject.write(data)
C. fileobject.close()
D. break
Answer: B. fileobject.write(data)
Explanation
Explanation:
In Program 2-3 (from NCERT Class 12, Chapter 2: File Handling in Python), the user is asked to input text repeatedly until they decide to stop. The line:fileobject.write(data)is the key statement that writes the entered string into the file.
input()only collects the data from the user.write()actually transfers it to the file.close()finalizes the operation and releases the resource.breaksimply exits the loop.Hence,
fileobject.write(data)is responsible for writing the input text into the file.
167. How does Program 2-4 traverse the entire file?
A. Using for line in fileobject
B. Using while str: with readline()
C. Using read() in a loop
D. Using seek() only
Answer: B. Using while str: with readline()
Explanation
Explanation:
In Program 2-4 (from NCERT Class 12 Computer Science – File Handling in Python), the program reads a text file line by line using awhileloop:str = fileobject.readline() while str: print(str) str = fileobject.readline()Here’s how it works:
readline()reads one line at a time from the file.- When the end of the file (EOF) is reached,
readline()returns an empty string (”), making the conditionwhile str:False, thus ending the loop.- This process ensures complete traversal of the file from start to end.
168. Which of the following is a correct sequence to write and then display a file?
A. Open → traverse → write → close
B. Open in write mode → write → close → open in read mode → traverse → close
C. Open → read → write → close
D. Open → append → read → overwrite → close
Answer: B. Open in write mode → write → close → open in read mode → traverse → close
Explanation
Explanation:
When you want to first write data to a file and then display (read) it, you must follow a logical sequence:Open file in write mode (‘w’) – this creates a new file or overwrites an existing one.
f = open("example.txt", "w")Write data to the file.
f.write("Hello, Python file handling!")Close the file.
This step is essential — it flushes the buffer and ensures data is properly saved to disk.f.close()Reopen the file in read mode (‘r’).
f = open("example.txt", "r")Traverse or display file content (e.g., using read(), readline(), or a loop).
print(f.read())Close the file again after reading.
f.close()This two-step process — write first, then read — ensures the written data is stored before being accessed.
169. What will happen if user enters empty string in Program 2-3?
A. Nothing is written
B. File is deleted
C. Empty line is written
D. Error occurs
Answer: C. Empty line is written
Explanation
Explanation:
In Python, thewrite()method writes exactly the string provided to it — even if that string is empty ("") or contains only a newline ("\n").So, if the user enters an empty string in Program 2-3 (which takes user input and writes it to a text file), the following happens:
data = input("Enter data: ") # User presses Enter without typing anything fileobject.write(data + "\n")
- Since
datais an empty string (""),data + "\n"becomes just"\n".- As a result, a blank line (newline) is written to the file.
- The file is not deleted and no error occurs.
This means every time the user presses Enter without typing text, a new empty line gets added.
Example Output:
If user inputs:
Hello <Enter> PythonThen the file content will be:
Hello Python(Notice one blank line between “Hello” and “Python.”)
170. Why is it recommended to use ‘w+‘ instead of ‘w‘ sometimes?
A. Allows reading after writing
B. Appends data
C. Deletes old file
D. Only works in binary
Answer: A. Allows reading after writing
Explanation
Explanation:
In Python, the difference between'w'and'w+'lies in what operations are permitted on the file.
'w'mode:
- Opens a file for writing only.
- Overwrites the file if it already exists.
- You cannot read from the file in this mode.
Example:
f = open("demo.txt", "w")
f.write("Hello")
print(f.read()) # Error: not readable
'w+'mode:
- Opens the file for both writing and reading.
- Also overwrites existing content (like
'w').- Useful when you want to write some data and then read it immediately in the same program.
Example:
f = open("demo.txt", "w+")
f.write("Python File Handling")
f.seek(0) # Move pointer to start
print(f.read()) # Output: Python File Handling
f.close()When to use
'w+':
If you want to:
- Write data to a file and then verify or read it back,
- Or perform both operations within one open() call,
then'w+'mode is ideal.
171. What is the purpose of opening a file in 'w+' mode?
A. Read-only
B. Write-only
C. Read and write; overwrites if file exists
D. Append-only
Answer: C. Read and write; overwrites if file exists
Explanation
Explanation:
The'w+'mode in Python opens a file for both reading and writing, with one key behavior — it erases the existing content of the file.Here’s how it works:
- If the file already exists, its content is deleted (overwritten).
- If the file does not exist, a new empty file is created.
- After opening, you can perform both write() and read() operations on the same file.
Example:
f = open("data.txt", "w+") f.write("Hello Python") f.seek(0) # Move pointer to start print(f.read()) # Output: Hello Python f.close()In the above example:
- The file is opened (created if not present).
- Data
"Hello Python"is written.seek(0)moves the pointer to the beginning.read()reads the content back.Key Points:
'w+'→ Read + Write (Overwrites file)'r+'→ Read + Write (Requires existing file; does not overwrite)'a+'→ Append + Read (Adds data at the end)
172. In Program 2-5, what does fileobject.write('\n') do?
A. Writes data without newline
B. Moves file pointer to next line
C. Reads the next line
D. Overwrites previous content
Answer: B. Moves file pointer to next line
Explanation
Explanation:
When you execute the statement:fileobject.write('\n')it writes a newline character (
\n) into the file.
This does not move the file pointer automatically like in a text editor, but when the file is later read (or displayed in Notepad), this newline character causes the next piece of written text to appear on a new line.Essentially,
'\n'represents a line break in text files.Example:
f = open("example.txt", "w") f.write("First line") f.write('\n') f.write("Second line") f.close()Content of example.txt:
First line Second lineKey Points:
'\n'is a special escape sequence that represents a newline character.- In Windows, it is interpreted as
\r\nwhen saved to file.- It is often used to ensure data written by multiple
write()calls appear on separate lines.
173. What does fileobject.tell() return?
A. Size of the file in bytes
B. Current byte position of file object
C. Number of lines in the file
D. Content of the file
Answer: B. Current byte position of file object
Explanation
Explanation:
Thetell()method in Python returns the current position of the file pointer (in bytes) from the beginning of the file.
This helps track where the next read or write operation will occur.Example:
f = open("sample.txt", "w+") f.write("Python File Handling") print(f.tell()) # Output: 21Here, the output
21indicates that the file pointer is 21 bytes from the start — because the string"Python File Handling"has 21 characters (including spaces).Key Points:
- The return value of
tell()is always an integer (byte position).- The pointer position changes automatically with each read/write operation.
- To move the pointer manually, we use the
seek(offset[, whence])method.
174. What is the effect of fileobject.seek(0) in Program 2-5?
A. Moves the file object to end of file
B. Moves the file object to beginning of file
C. Reads the first line
D. Deletes the file
Answer: B. Moves the file object to beginning of file
Explanation
Explanation:
Theseek(0)method call repositions the file pointer to the 0th byte, i.e., the beginning of the file.
This is particularly useful when you’ve written data to a file and want to read it again from the start without reopening it.Example:
f = open("example.txt", "w+") f.write("Python Programming") f.seek(0) print(f.read()) f.close()Output:
Python ProgrammingHere,
seek(0)ensures that the file pointer moves back to the start so theread()function can access the entire file content.Key Points:
- The syntax is:
fileobject.seek(offset, whence)
offset=0→ byte positionwhence=0→ beginning of file (default)- Commonly used after writing data when you want to read the same file immediately.
- Does not modify file content; it only changes pointer position.
175. Why is a single file object used in Program 2-5?
A. To reduce memory usage
B. To perform simultaneous read and write on the same file
C. To make file read-only
D. To avoid newline characters
Answer: B. To perform simultaneous read and write on the same file
Explanation
Explanation:
In Program 2-5, the file is opened using the ‘w+’ mode, which allows both writing and reading operations on the same file object.
This means that after writing data to the file, we can use methods likeseek()andread()with the same object to read the contents — without closing and reopening the file.Example:
f = open("example.txt", "w+") f.write("Python File Handling") f.seek(0) print(f.read()) f.close()Output:
Python File HandlingHere, the same file object
fis used for writing and then reading, made possible by'w+'mode.Key Points:
'w+'→ Read and write mode; overwrites existing file content.seek(0)→ Moves the file pointer back to the beginning before reading.- Saves time and memory since no new object is created for reading.
- Useful for quick file updates and verification after writing.
176. What happens if we try to read() immediately after opening a file in 'w+' mode without writing any data?
A. Reads garbage values
B. Returns empty string
C. Error occurs
D. Deletes file
Answer: B. Returns empty string
Explanation
Explanation:
When a file is opened in ‘w+’ mode, Python does two things automatically:
- Creates a new file if it doesn’t exist.
- Clears (overwrites) the file if it already exists.
This means that immediately after opening, the file is completely empty.
So, if we callread()right away, there’s no content to read, and it returns an empty string (''), not an error.Example:
f = open("demo.txt", "w+") data = f.read() print(data) f.close()Output:
'' # (Empty string)Key Points:
'w+'→ Opens file for both reading and writing, but clears existing data.read()on an empty file returns''.- To read meaningful data, you must first write to the file, then use
seek(0)to move the pointer to the start before reading again.
177. In Program 2-5, why is fileobject.seek(0) called before reading?
A. To move the file pointer to EOF
B. To move the file pointer to the beginning for reading
C. To write newline
D. To close the file
Answer: B. To move the file pointer to the beginning for reading
Explanation
Explanation:
When a file is opened in'w+'mode, it allows both writing and reading using the same file object.
However, after performing a write() operation, the file pointer moves to the end of the file.
If we call read() immediately, Python starts reading from the current pointer position — which is the end of the file — and therefore returns an empty string.To correctly read the written data, we must first reset the pointer to the start of the file using:
fileobject.seek(0)This moves the pointer back to byte position 0, so that subsequent read() operations begin from the start of the file content.
Example:
f = open("demo.txt", "w+") f.write("Python File Handling") f.seek(0) print(f.read()) f.close()Output:
Python File HandlingKey Points:
seek(0)moves the file pointer to the beginning.- Without it,
read()afterwrite()returns an empty string.- Essential when using
'w+','a+', or'r+'modes for both reading and writing.
178. What will happen if fileobject.close() is not called after Program 2-5 execution?
A. File will not save data properly
B. File pointer resets automatically
C. Data will be lost
D. No effect
Answer: A. File will not save data properly
Explanation
Explanation:
When a file is opened for writing (in'w','w+','a', or'a+'mode), the data is not immediately written to the disk.
Instead, it is temporarily stored in a buffer (a small memory area).The function
fileobject.close()performs two essential tasks:
- Flushes the buffer — meaning all data in memory is physically written to the file on disk.
- Releases system resources — freeing the file handle used by the operating system.
If you don’t call
close(), and the program ends abruptly (e.g., due to an error or termination), the buffered data might never be saved properly, leading to incomplete or lost file content.Example:
f = open("test.txt", "w+") f.write("Python File Handling Example") # f.close() is missingIn this example, the data might not appear in
test.txtbecause it’s still sitting in the buffer.
Addingf.close()ensures the data is written correctly:f.close()Important Notes:
close()is mandatory when working with file writing.- You can also use the with statement to auto-close the file safely:
with open("test.txt", "w+") as f:
f.write("Data is automatically saved and closed.")
179. Which statement reads the entire content after writing in Program 2-5?
A. fileobject.readline()
B. fileobject.readlines()
C. fileobject.read()
D. fileobject.write()
Answer: C. fileobject.read()
Explanation
Explanation:
The methodread()is used to read the entire content of a file as a single string from the current file pointer position until the end of file (EOF).In Program 2-5, the sequence is:
- The file is opened in
'w+'mode, allowing both writing and reading.- Some data is written to the file using
write().- Then, before reading,
fileobject.seek(0)is used to move the pointer back to the beginning.- Finally,
fileobject.read()reads the entire content from the start till the end.Example:
fileobject = open("example.txt", "w+") fileobject.write("Python File Handling\nRead and Write Example") fileobject.seek(0) # Move pointer to beginning data = fileobject.read() # Reads the entire content print(data) fileobject.close()Output:
Python File Handling Read and Write ExampleKey Difference from Other Methods:
Method Description read()Reads entire file as a single string readline()Reads only one line from the file readlines()Reads all lines and returns a list of strings write()Writes data to file (does not read) Important Notes:
- Always use
seek(0)before reading after writing; otherwise,read()will return an empty string since the pointer is at EOF.- After reading, the pointer moves to the end of the file again.
180. What will fileobject.tell() output if two sentences of 34 and 33 characters were written with \n after each?
A. 69
B. 34
C. 33
D. 0
Answer: A. 69
Explanation
Explanation:
Thetell()method in Python returns the current position of the file pointer in bytes from the beginning of the file.
It counts every character, including spaces, punctuation, and newline (\n) characters.Step-by-Step Calculation:
- First sentence: 34 characters
- Newline after first sentence: +1 byte
- Second sentence: 33 characters
- Newline after second sentence: +1 byte
So,
Total bytes written = 34 + 1 + 33 + 1 = 69 bytesTherefore, after both write operations,
fileobject.tell() # returns 69Example (to verify):
f = open("test.txt", "w+") f.write("A" * 34 + "\n") f.write("B" * 33 + "\n") print(f.tell()) f.close()Output:
69
181. Why do we use a while True loop in Program 2-5?
A. To repeat file writing until user stops
B. To read EOF
C. To move file pointer
D. To overwrite file
Answer: A. To repeat file writing until user stops
Explanation
Explanation:
In Program 2-5, the statement:while True: data = input("Enter data: ") fileobject.write(data + '\n') ans = input("Do you wish to enter more data? (y/n): ") if ans == 'n': breakcreates a continuous loop that keeps accepting user input indefinitely — until the user explicitly decides to stop.
Key Concept:
while True:
→ Creates an infinite loop that executes repeatedly.breakstatement
→ Terminates the loop when a certain condition is met (in this case, when the user types'n').Thus, this structure allows the program to keep writing data to the file until the user chooses to stop.
Why it’s used in file handling:
- Makes the program interactive.
- Allows multiple entries without knowing how many lines the user will input.
- Prevents code repetition by using a single controlled loop.
Example Output Behavior:
Enter data: Hello Do you wish to enter more data? (y/n): y Enter data: Python File Handling Do you wish to enter more data? (y/n): nAt this point, the loop stops and the file is closed.
182. What is printed after reading the file in Program 2-5?
A. Only last line written
B. Entire file content written till that point
C. Nothing
D. Error
Answer: B. Entire file content written till that point
Explanation
Explanation:
In Program 2-5, after writing data to the file, the code typically contains the following lines:fileobject.seek(0) print(fileobject.read())Step-by-step explanation:
seek(0)— This command moves the file pointer to the beginning of the file.
- After writing, the pointer is at the end, so without calling
seek(0),read()would return an empty string.read()— This method reads the entire content of the file from the current pointer position (which is now the beginning) until the end of the file (EOF).print()— Displays all the text that has been written in the file up to that point.Hence, the output shows the complete file content written so far.
seek(0) moves the pointer to the start, and read() reads the full content from beginning to end, displaying everything written so far.
Example:
fileobject = open("practice.txt", "w+") fileobject.write("Python File Handling\n") fileobject.write("Program 2-5 Example\n") fileobject.seek(0) print(fileobject.read()) fileobject.close()Output:
Python File Handling Program 2-5 Example
183. Which of the following is TRUE about w+ mode?
A. Appends data without overwriting
B. Deletes existing content before writing
C. Opens file as binary
D. Read-only mode
Answer: B. Deletes existing content before writing
Explanation
Explanation:
Thew+mode in Python opens a file for both reading and writing, but with one important behavior:
- If the file already exists, it is completely cleared (truncated to zero length) before any new data is written.
- If the file does not exist, it is created automatically.
After opening, you can both write() and read() using the same file object.
However, since the file is emptied first, any previously saved data is lost.Key Points:
w+= write and read mode (not append).- Existing content is deleted immediately upon opening.
- Pointer starts at the beginning of an empty file.
- You can use
seek(0)to reposition pointer for reading after writing.Example:
file = open("demo.txt", "w+") file.write("Hello, Python!") file.seek(0) print(file.read()) file.close()Output:
Hello, Python!If
demo.txtcontained previous data, it would be erased before writing the new content.
184. Which statement is responsible for displaying the byte position of file pointer?
A. fileobject.read()
B. fileobject.seek(0)
C. fileobject.tell()
D. fileobject.write()
Answer: C. fileobject.tell()
Explanation
Explanation:
In Python, every file opened usingopen()has a file pointer that tracks the current position (in bytes) within the file.
Thetell()method is used to retrieve that position — i.e., it tells you where the next read or write operation will occur.
- The value returned by
tell()is an integer, representing the number of bytes from the beginning of the file.- This method is especially useful after operations like
read(),write(), orseek()to understand where the pointer currently is.Key Points:
tell()→ returns the current position of the file pointer (in bytes).seek(offset)→ moves the pointer to a specific position.read()andwrite()automatically move the pointer forward.- The pointer position starts at 0 when the file is first opened.
Example:
file = open("demo.txt", "w+") file.write("Python File Handling") print(file.tell()) # Display current position file.seek(0) print(file.read()) file.close()Output:
21 Python File HandlingAfter writing"Python File Handling"(21 characters), the file pointer is at byte position 21, whichtell()reports.
185. Why is print() used after "WRITING DATA IN THE FILE"?
A. To execute the write method
B. To display a blank line for better formatting
C. To move file pointer
D. To close file
Answer: B. To display a blank line for better formatting
Explanation
Explanation:
In Python, whenprint()is used without any arguments, it simply prints a newline (\n), which creates a blank line in the output.
In programs like Program 2-5 (File Handling), it is often used after printing headings or messages such as"WRITING DATA IN THE FILE"to make the program output more readable and neatly formatted.This blank line acts as a visual separator between different stages of file operations — such as writing and reading — making the output easier to understand for the user.
Key Points:
print()with no arguments → prints a blank line.- Improves output readability by separating sections.
- Has no effect on the file pointer or file operations.
- Used purely for output formatting on the console.
Example:
print("WRITING DATA IN THE FILE") print() # Prints a blank line print("READING DATA FROM THE FILE")Output:
WRITING DATA IN THE FILE READING DATA FROM THE FILEThe second print() adds a blank line between the two messages, improving the clarity of output.
186. What is the purpose of the pickle module in Python?
A. To read/write text files
B. To store Python objects as byte streams
C. To execute Python code
D. To create CSV files
Answer: B. To store Python objects as byte streams
Explanation
Explanation:
Thepicklemodule in Python is used for object serialization — the process of converting Python objects (like lists, dictionaries, tuples, classes, etc.) into a byte stream that can be written to a binary file or transmitted over a network.This process is called pickling, and the reverse process — converting the byte stream back into a Python object — is called unpickling.
By using the
picklemodule, you can save complex Python data structures permanently and retrieve them later without losing their structure or data type.Key Points:
- Pickling: Converting a Python object into a byte stream.
- Unpickling: Converting the byte stream back to the original object.
- Used for: Storing or transferring Python objects efficiently.
- File type: Usually binary (
.dator.pklfiles).- Important methods:
pickle.dump(object, file)→ Write object to file.pickle.load(file)→ Read object from file.Example:
import pickle data = {'name': 'Ravi', 'age': 21, 'marks': [85, 90, 95]} file = open('student.dat', 'wb') # open in binary write mode pickle.dump(data, file) # serialize and save object file.close()Later, to read the object back:
file = open('student.dat', 'rb') # open in binary read mode data_loaded = pickle.load(file) # deserialize (unpickle) file.close() print(data_loaded)Output:
{'name': 'Ravi', 'age': 21, 'marks': [85, 90, 95]}
187. Pickling in Python is analogous to:
A. Reading a text file
B. Writing a Python object to a file as a byte stream
C. Deleting a file
D. Converting a string to integer
Answer: B. Writing a Python object to a file as a byte stream
Explanation
Explanation:
Pickling is the process of serializing a Python object — that is, converting it from its in-memory form (such as a list, dictionary, or class object) into a sequence of bytes.
These bytes can then be written to a binary file, stored, or transmitted over a network.When the data is later needed, it can be unpickled (deserialized) — converted back from the byte stream into the original Python object with the same structure and values.
Analogy:
Just like writing text data to a text file using
write(),
→ pickling writes object data to a binary file usingpickle.dump().Key Concepts:
Term Meaning Pickling Converting Python object → byte stream Unpickling Converting byte stream → Python object dump() Used to write (pickle) object to file load() Used to read (unpickle) object from file Module used pickleExample:
import pickle student = {'name': 'Aman', 'age': 18, 'marks': 92} # Pickling (Serialization) with open('student.dat', 'wb') as f: pickle.dump(student, f)This saves the dictionary
studentin binary form inside student.dat.Reverse Process (Unpickling):
import pickle with open('student.dat', 'rb') as f: data = pickle.load(f) print(data)Output:
{'name': 'Aman', 'age': 18, 'marks': 92}
188. What is the opposite of pickling?
A. Serialization
B. Unpickling
C. Encoding
D. Compiling
Answer: B. Unpickling
Explanation
Explanation:
Pickling and Unpickling are two opposite processes handled by Python’spicklemodule.
- Pickling (Serialization):
Converts a Python object (like list, dict, tuple, class object) into a byte stream, so it can be stored in a binary file or sent over a network.- Unpickling (Deserialization):
Converts that byte stream back into the original Python object in memory.Thus, unpickling is the reverse (or opposite) of pickling.
Key Concepts Table:
Process Definition Function Used File Mode Pickling Object → Byte Stream pickle.dump()'wb'Unpickling Byte Stream → Object pickle.load()'rb'Example:
import pickle # Pickling student = {'name': 'Mohan Exam', 'age': 18} with open('student.dat', 'wb') as f: pickle.dump(student, f) # Unpickling with open('student.dat', 'rb') as f: data = pickle.load(f) print(data)Output:
{'name': 'Mohan Exam', 'age': 18}Here,
- The dictionary
studentis first pickled (saved as bytes).- Then it’s unpickled (restored to original form).
In Simple Terms:
- Pickling → Saving
- Unpickling → Loading
189. Which of the following modes should be used to dump a Python object using pickle?
A. 'r'
B. 'w'
C. 'wb'
D. 'a+'
Answer: C. 'wb'
Explanation
Explanation:
The pickle module stores Python objects as binary data, not plain text.
Hence, when writing (dumping) an object into a file, the file must be opened in binary write mode ('wb').If you use only
'w', the file expects text data, and pickling will raise an error because the dump function produces bytes, not strings.Key Concept Table:
Operation Function File Mode Description Pickling (Writing) pickle.dump(object, file)'wb'Writes Python object as bytes Unpickling (Reading) pickle.load(file)'rb'Reads bytes and restores the object Example:
import pickle data = {'name': 'Mohan Exam', 'subject': 'Computer Science'} # Pickling (writing) with open('datafile.dat', 'wb') as f: pickle.dump(data, f)Explanation:
'wb'opens the file in binary write mode.pickle.dump()converts the Python objectdatainto bytes and writes it to the file.In Simple Terms:
Pickle = Binary Data
Therefore, use'wb'for writing and'rb'for reading.
190. What is the correct syntax of the dump() method in the pickle module?
A. dump(fileobject, dataobject)
B. dump(dataobject, fileobject)
C. dump(dataobject)
D. dump(fileobject)
Answer: B. dump(dataobject, fileobject)
Explanation
Explanation:
Thedump()method is used to serialize (pickle) a Python object and write it into a binary file.
- The first argument is the object to be pickled.
- The second argument is the file object opened in binary write mode (
'wb').If the order is reversed, Python will raise a TypeError.
Syntax:
pickle.dump(object, file)Example:
import pickle data = {'name': 'Mohan Exam', 'subject': 'Computer Science'} with open('datafile.dat', 'wb') as f: pickle.dump(data, f)Here,
data→ Python object (to be stored)f→ file object (destination)Key Points:
Function Purpose File Mode pickle.dump(obj, file)Write (pickle) object 'wb'pickle.load(file)Read (unpickle) object 'rb'
191. Which method is used to retrieve (load) a Python object from a file?
A. dump()
B. load()
C. read()
D. write()
Answer: B. load()
Explanation
Explanation:
Theload()method in the pickle module is used to deserialize (unpickle) a Python object from a binary file.
- It reads the byte stream produced by
dump().- Then, it reconstructs the original Python object in memory.
If you try to use
read()instead ofload()on a pickled file, you’ll only get raw binary data — not the actual Python object.Syntax:
pickle.load(fileobject)Example:
import pickle with open('datafile.dat', 'rb') as f: data = pickle.load(f) print(data)Output:
{'name': 'Mohan Exam', 'subject': 'Computer Science'}Key Points:
Function Purpose File Mode pickle.dump(obj, file)Serializes and writes object 'wb'pickle.load(file)Deserializes and reads object 'rb'
192. Why must we open the file in binary mode for pickle operations?
A. Because pickle writes strings
B. Because pickle works with byte streams
C. Because binary mode speeds up writing
D. Because text files are read-only
Answer: B. Because pickle works with byte streams
Explanation
Explanation:
The pickle module serializes Python objects into a binary format (byte stream).
Binary mode ('wb'for writing,'rb'for reading) ensures that these bytes are written and read exactly as they are, without any text encoding or newline conversions.If you try to open the file in text mode (
'w'or'r'), the binary data could get corrupted because text mode interprets certain bytes (like\n,\r) differently depending on the operating system.Example:
import pickle data = {'name': 'Mohan Exam', 'subject': 'Python'} # Writing (Pickling) with open('datafile.dat', 'wb') as f: pickle.dump(data, f) # Reading (Unpickling) with open('datafile.dat', 'rb') as f: obj = pickle.load(f) print(obj)Output:
{'name': 'Mohan Exam', 'subject': 'Python'}Key Point Table:
Operation Function File Mode Pickling (write) pickle.dump(obj, file)'wb'Unpickling (read) pickle.load(file)'rb'
193. Which of the following can be pickled using the pickle module?
A. Lists and dictionaries
B. Tuples and sets
C. Custom Python objects
D. All of the above
Answer: D. All of the above
Explanation
Explanation:
The pickle module in Python can serialize (convert into byte stream) almost any Python object —
including built-in data structures like lists, tuples, sets, dictionaries, and even user-defined class objects.When these objects are pickled, Python internally converts their structure and data into a binary representation, which can later be unpickled (deserialized) to restore them exactly as they were.
However, some objects such as open file handles, database connections, or lambda functions cannot be serialized using pickle.
Example:
import pickle data = { 'name': 'Mohan Exam', 'marks': [95, 89, 92], 'subjects': ('Python', 'CS', 'AI') } # Pickling the object with open('student.dat', 'wb') as f: pickle.dump(data, f) # Unpickling the object with open('student.dat', 'rb') as f: result = pickle.load(f) print(result)Output:
{'name': 'Mohan Exam', 'marks': [95, 89, 92], 'subjects': ('Python', 'CS', 'AI')}Key Notes:
Object Type Picklable Example List Yes [1, 2, 3]Dictionary Yes {'a': 1, 'b': 2}Tuple Yes (1, 2, 3)Set Yes {1, 2, 3}Class object Yes Custom Python class instances Open file / lambda No Not supported by pickle
194. What happens if we try to read a pickled file in text mode ('r')?
A. Object is loaded successfully
B. Garbage characters or error
C. File is overwritten
D. Nothing happens
Answer: B. Garbage characters or error
Explanation
Explanation:
Pickled files are binary files — they contain byte streams, not human-readable text.
When such a file is opened in text mode (‘r’), Python tries to decode the binary data as text (usually UTF-8).Since pickled data doesn’t follow text encoding rules, one of the following occurs:
- Unreadable garbage symbols appear on the screen, or
- A UnicodeDecodeError (or similar decoding error) is raised.
To properly handle pickled files, you must always use binary modes —
'wb'for writing (dumping) objects'rb'for reading (loading) objectsExample:
import pickle data = {'name': 'Mohan Exam', 'score': 95} # Pickling the object with open('datafile.dat', 'wb') as f: pickle.dump(data, f) # Wrong way — opening in text mode with open('datafile.dat', 'r') as f: print(f.read()) # This will show garbage or raise an errorOutput (example):
��}q(XnameqXMoh...or
UnicodeDecodeError: 'utf-8' codec can't decode byte 0x80 in position 0Key Concept Table:
Mode Description Use With Pickle 'r'/'w'Text mode Not suitable 'rb'Read binary For pickle.load()'wb'Write binary For pickle.dump()
195. Which module is mandatory for pickling in Python?
A. io
B. pickle
C. os
D. csv
Answer: B. pickle
Explanation
Explanation:
Pickling is the process of serializing (converting) a Python object into a byte stream so that it can be stored in a file or transmitted over a network.
To perform this process, Python provides a built-in module namedpickle.The
picklemodule includes two main functions:
pickle.dump(obj, file)→ writes (pickles) an object to a binary file.pickle.load(file)→ reads (unpickles) the object back from the file.Without importing the
picklemodule, these operations cannot be performed.Example:
import pickle data = {'site': 'Mohan Exam', 'topic': 'File Handling'} # Pickling the object with open('datafile.dat', 'wb') as f: pickle.dump(data, f) # Unpickling the object with open('datafile.dat', 'rb') as f: obj = pickle.load(f) print(obj)Output:
{'site': 'Mohan Exam', 'topic': 'File Handling'}Key Concept Table:
Function Purpose Mode Used pickle.dump(obj, file)Write (pickle) object 'wb'pickle.load(file)Read (unpickle) object 'rb'
196. Which of the following is TRUE about pickling?
A. Pickled files are human-readable
B. Pickled files can only store integers
C. Pickled files are binary representations of objects
D. Pickled files can only be used in text mode
Answer: C. Pickled files are binary representations of objects
Explanation
Explanation:
Pickling is the process of converting a Python object into a byte stream (binary form) so that it can be stored in a file or transmitted.
This means that pickled files are not human-readable, as they store data in a binary format rather than plain text.When using pickling, the file must be opened in binary mode (
'wb'for writing and'rb'for reading`).Example:
import pickle data = ['Mohan Exam', 2025, True] # Pickling the data with open('data.pkl', 'wb') as file: pickle.dump(data, file)If you open
data.pklin a text editor, you will see unreadable binary symbols — confirming that it is not human-readable.Key Points:
- Pickled files store binary data.
- They can store any Python object (lists, dictionaries, tuples, custom objects, etc.).
- They must be opened in binary mode.
197. If we want to store the current state of a game in Python, which module is most suitable?
A. csv
B. pickle
C. os
D. json
Answer: B. pickle
Explanation
Explanation:
Thepicklemodule is ideal for saving and restoring complex Python objects such as game states, levels, player scores, and configurations.
It converts entire Python objects into a binary byte stream (process called pickling) and can later recreate the same objects (unpickling).Unlike
csvorjson, which can only handle simple data types (strings, numbers, lists, dicts),picklecan store custom classes, nested structures, and object references, making it perfect for saving in-memory game data.Example:
import pickle game_state = { 'level': 5, 'score': 3400, 'player_position': (120, 250) } # Save the game state with open('savegame.pkl', 'wb') as file: pickle.dump(game_state, file) # Load the game state with open('savegame.pkl', 'rb') as file: loaded_state = pickle.load(file) print(loaded_state)Key Points:
- Pickling = Serialization → converts objects to bytes.
- Unpickling = Deserialization → converts bytes back to objects.
- Works best for storing custom or complex data structures.
- Files must be opened in binary mode (
'wb'/'rb').
198. What will happen if we try to dump a file object itself using the pickle module?
A. Works fine
B. Error occurs
C. File is overwritten
D. File is deleted
Answer: B. Error occurs
Explanation
Explanation:
Thepicklemodule can serialize most Python objects such as lists, dictionaries, tuples, and even user-defined classes.
However, certain objects cannot be pickled, including open file objects, database connections, network sockets, and lambda functions.If you attempt to
pickle.dump()a file object (like one returned byopen()), Python raises aTypeErrorbecause open file objects refer to system-level resources that cannot be represented as byte streams.Example:
import pickle f = open("data.txt", "w") try: pickle.dump(f, open("file.pkl", "wb")) except Exception as e: print("Error:", e)Output:
Error: cannot pickle '_io.TextIOWrapper' objectKey Points:
pickleonly works with serializable objects (data structures).- Open file handles, sockets, and threads cannot be pickled.
- This restriction exists because such objects depend on active system resources, which can’t be reconstructed from bytes.
199. Pickle is best suited for which type of data storage?
A. Temporary memory (RAM)
B. Permanent storage as binary objects
C. Plain text CSV files
D. HTML data
Answer: B. Permanent storage as binary objects
Explanation
Explanation:
Thepicklemodule in Python is designed for object serialization, which means converting Python objects into a byte stream that can be saved to a file and retrieved later.
This makes it ideal for permanent data storage of Python-specific data structures — such as lists, dictionaries, classes, and custom objects — in a binary format.Unlike CSV or text files that store data in human-readable form, pickle stores data in a format optimized for the Python interpreter, allowing objects to be reloaded exactly as they were.
Example:
import pickle data = {"name": "MohanExam", "students": 150, "topic": "Python File Handling"} # Save (Pickle) with open("data.pkl", "wb") as file: pickle.dump(data, file) # Load (Unpickle) with open("data.pkl", "rb") as file: result = pickle.load(file) print(result)Output:
{'name': 'MohanExam', 'students': 150, 'topic': 'Python File Handling'}Key Points:
- Pickle allows persistent storage of Python objects in binary files.
- It is language-dependent (i.e., data pickled in Python cannot be easily used in other languages).
- Ideal for saving program states, machine learning models, and complex data structures.
200. Which statement is correct regarding load() method?
A. It writes an object to a file
B. It reads the byte stream and returns a Python object
C. It deletes the file
D. It converts an object to string
Answer: B. It reads the byte stream and returns a Python object
Explanation
Explanation:
Theload()method in thepicklemodule is used for unpickling — that is, it reads the binary data (byte stream) from a file and reconstructs the original Python object that was previously pickled.When you call
pickle.load(file), it takes the binary data stored in the file and converts it back into the exact Python object (like a list, dictionary, or custom class instance) that was saved earlier usingpickle.dump().Example:
import pickle # Unpickling example with open("data.pkl", "rb") as file: obj = pickle.load(file) print(obj)Output:
{'name': 'MohanExam', 'students': 150, 'topic': 'Python File Handling'}Key Points:
load()→ Reads from a binary file and reconstructs the object.- Must open the file in binary read mode (‘rb’).
- The object returned by
load()is identical in type and structure to the one saved withdump().- If the file is not a valid pickle file, it raises an
UnpicklingError.
201. What is stored in the file mybinary.dat in Program 2-6?
A. Text data only
B. Python list object as binary data
C. CSV formatted string
D. JSON data
Answer: B. Python list object as binary data
Explanation
Explanation:
In Program 2-6 (from NCERT Class 12 Computer Science, Chapter 2: File Handling in Python), the statement:pickle.dump([1, "Geetika", 'F', 26], f)is used to store a Python list object inside a binary file named
mybinary.dat.Here, the
pickle.dump()function converts the list[1, "Geetika", 'F', 26]into a binary byte stream (a sequence of bytes), and writes it into the file.
This process is called Pickling (Serialization).As a result, the file does not contain readable text, but rather binary-encoded data representing the list structure and its elements.
Example:
import pickle data = [1, "Geetika", 'F', 26] # Writing binary data (Pickling) with open("mybinary.dat", "wb") as f: pickle.dump(data, f) # Reading binary data (Unpickling) with open("mybinary.dat", "rb") as f: obj = pickle.load(f) print(obj)Output:
[1, 'Geetika', 'F', 26]Key Points:
- The file
mybinary.datcontains the binary representation of the list object.- It is not human-readable.
- It must be opened using the
'wb'(write binary) and'rb'(read binary) modes.- To read it back, use
pickle.load().
202. Which file mode is used for pickling (writing) in Program 2-6?
A. 'r'
B. 'w'
C. 'wb'
D. 'a+'
Answer: C. 'wb'
Explanation
Explanation:
When performing pickling (i.e., writing Python objects in binary form), the file must be opened in binary write mode (‘wb’).
This ensures that Python writes byte streams instead of normal text.In Program 2-6, the file is opened as:
f = open('mybinary.dat', 'wb')Then, the data is stored using:
pickle.dump([1, "Geetika", 'F', 26], f)Here:
'wb'= write binary mode, used for pickling'rb'= read binary mode, used for unpicklingIf you mistakenly use
'w'or'r', it will cause an error becausepicklerequires a binary file stream.Example:
import pickle data = [1, "Geetika", 'F', 26] # Pickling (writing binary) with open("mybinary.dat", "wb") as f: pickle.dump(data, f)This code writes the Python list as binary data into
mybinary.dat.Key Points:
'wb'→ Used for writing binary data (pickling)'rb'→ Used for reading binary data (unpickling)- Required by
picklemodule to serialize objects properly.
203. What will happen if we try to open mybinary.dat in text mode ('r') and read it?
A. Data is displayed correctly
B. Garbage characters appear
C. Python automatically converts it to text
D. File is overwritten
Answer: B. Garbage characters appear
Explanation
Explanation:
Pickled files contain binary data — i.e., data stored in the form of byte streams, not plain text.
If you open such a file using text mode'r', Python will attempt to interpret binary bytes as text characters, which results in unreadable or garbage output.For example:
f = open("mybinary.dat", "r") print(f.read())Output will look like:
�€•€‡}q(X...These are nonsensical characters because binary bytes don’t correspond to readable text encoding.
To properly read this file, you must use binary read mode (‘rb’) along with
pickle.load():import pickle with open("mybinary.dat", "rb") as f: data = pickle.load(f) print(data)This correctly reconstructs the original Python object (e.g.,
[1, "Geetika", 'F', 26]).Key Points:
- Pickled files are not human-readable.
- Use
'rb'mode withpickle.load()for unpickling.- Reading binary data in text mode causes garbled output or sometimes UnicodeDecodeError.
204. Which method is used to retrieve data from mybinary.dat in Program 2-7?
A. read()
B. load()
C. write()
D. writelines()
Answer: B. load()
Explanation
Explanation:
In Python, when data is stored in a binary file using the pickle module, it is converted into a byte stream (serialized form).
To get this data back as a Python object, we use thepickle.load()method.
pickle.load(fileobject)reads the binary data from the file and deserializes (unpickles) it into its original form, such as a list, dictionary, or any Python object.For example:
import pickle with open("mybinary.dat", "rb") as f: data = pickle.load(f) print(data)Output:
[1, "Geetika", 'F', 26]Here,
load()has reconstructed the same Python object that was earlier stored usingpickle.dump().Key Points:
load()is the reverse operation ofdump().- The file must be opened in binary read mode (‘rb’).
- It converts the byte stream back to the original Python object.
- Using
read()orwritelines()would return raw binary data, not usable objects.
205. After executing Program 2-7, which data type will objectvar have?
A. String
B. List
C. Dictionary
D. Tuple
Answer: B. List
Explanation
Explanation:
In Program 2-6, the object[1, "Geetika", 'F', 26]was stored in a binary file (mybinary.dat) usingpickle.dump().
This object is a Python list.When Program 2-7 executes
objectvar = pickle.load(f), it reads the byte stream from the binary file and restores it to its original Python data type, which in this case is a list.Example:
import pickle with open("mybinary.dat", "rb") as f: objectvar = pickle.load(f) print(type(objectvar))Output:
<class 'list'>Thus,
objectvarbecomes a list object after unpickling.Key Points:
pickle.load()restores the same type of object that was stored usingpickle.dump().- The object’s structure and type are preserved during the pickling and unpickling process.
- Here, the original data was a list, so it remains a list after loading.
206. Why do we need to close the file after pickling/unpickling?
A. To free memory and ensure data is written to disk
B. It is optional
C. Python automatically closes all files
D. To convert the file to text
Answer: A. To free memory and ensure data is written to disk
Explanation
Explanation:
After performing pickling (pickle.dump()) or unpickling (pickle.load()), it is important to close the file usingfileobject.close().When a file is open, Python uses a buffer to temporarily hold data before writing it to disk.
If the file is not closed, this buffered data may not be fully written, leading to data loss or file corruption.Additionally, closing a file:
- Frees up the system memory used for the file operation.
- Ensures that resources (like file handles) are properly released.
- Makes the file ready for other programs to use safely.
Example:
import pickle data = [1, 2, 3] file = open("datafile.dat", "wb") pickle.dump(data, file) file.close() # Ensures all data is saved and resources freedKey Points:
- Always call
close()after file operations (whether text or binary).- Alternatively, use a with statement, which automatically closes the file:
with open("datafile.dat", "wb") as f: pickle.dump(data, f)- This ensures safe and complete writing of data to the disk.
207. In Program 2-8, the same file object is used to append and read records of employees. Which mode is most appropriate?
A. 'w'
B. 'wb'
C. 'ab+'
D. 'r+'
Answer: C. 'ab+'
Explanation
Explanation:
In Python, file mode'ab+'is used when we want to append data in binary format and also read from the same file.
'a'→ append mode (data is added to the end of the file, not overwritten)'b'→ binary mode (required for pickling)'+'→ allows both reading and writing in the same fileSo
'ab+'combines all these features — it lets you add new binary records (like pickled employee objects) and read existing ones without erasing the previous data.Example:
import pickle # Open file for both appending and reading in binary mode with open("employee.dat", "ab+") as file: emp = ["Ravi", 101, 35000] pickle.dump(emp, file)This mode is ideal for programs like Program 2-8, where:
- Employee records are stored as binary objects.
- New records are added without losing previous data.
- Reading is also required for verification or display.
Key Points:
'wb'→ overwrites existing data (not suitable for appending).'ab'→ append only (cannot read).'ab+'→ best choice for append + read in binary mode.
208. Which of the following statements is TRUE about pickle files?
A. Pickle files can be opened in Notepad and edited
B. Pickle files can store Python objects, including lists, tuples, dictionaries
C. Pickle files automatically convert to JSON
D. Pickle files are stored as plain text
Answer: B. Pickle files can store Python objects, including lists, tuples, dictionaries
Explanation
Explanation:
The pickle module in Python allows storing and retrieving almost any kind of Python object — such as lists, tuples, sets, dictionaries, and even user-defined classes.When data is pickled, it is converted into a binary byte stream, not human-readable text. Hence, pickled files cannot be edited or viewed using text editors like Notepad.
Example:
import pickle data = {'name': 'Mohan', 'age': 22, 'marks': [85, 90, 92]} with open("student.dat", "wb") as f: pickle.dump(data, f)Here, the dictionary object is serialized (pickled) and stored in binary format inside the file
student.dat.Key Points:
- Pickle can store complex Python objects.
- Files are stored in binary form (not human-readable).
- To view or load the data, we must use
pickle.load().- Pickle is different from JSON — it is Python-specific.
209. What happens if we try to unpickle a file that was never pickled?
A. Returns an empty object
B. Raises a pickle.UnpicklingError
C. Converts file to text
D. Deletes the file
Answer: B. Raises a pickle.UnpicklingError
Explanation
Explanation:
Concept Recap:
In Python, the Pickle module is used to serialize and deserialize Python objects.
- Pickling means converting a Python object (like a list, dictionary, or tuple) into a byte stream using
pickle.dump().- Unpickling means loading that byte stream back into memory as the original Python object using
pickle.load().When we use
pickle.load(), Python expects the file to contain binary data that was earlier generated by thepickle.dump()function.What happens if the file was never pickled?
If the file you’re trying to open contains plain text or no data at all, then it doesn’t have the special byte sequence that thepicklemodule understands.
As soon as Python starts reading it, it encounters invalid bytes that do not match the pickle format.
In that case, it raises this error:_pickle.UnpicklingError: invalid load key, 'H'.The
'H'or other character shown in the message refers to the first character in the invalid (non-pickle) file.Example:
import pickle # Trying to unpickle a normal text file with open("sample.txt", "rb") as f: data = pickle.load(f)If
sample.txtwas never pickled, Python will raise:_pickle.UnpicklingError: invalid load key, 'T'.This happens because the first character
'T'in"This is a text file"is not a valid pickle header.Key Point:
Unpickling requires that the file be in the exact binary format created bypickle.dump().
If not, Python immediately raises apickle.UnpicklingErrorto prevent corrupt or invalid data from being loaded.
210. Which of the following is required before using dump() or load()?
A. import os
B. import io
C. import pickle
D. No import required
Answer: C. import pickle
Explanation
Explanation:
Concept Recap:
In Python, thepicklemodule provides two main functions for object serialization (storing Python objects in a binary format):
pickle.dump(object, file)→ To write (pickle) a Python object into a binary file.pickle.load(file)→ To read (unpickle) that object back into memory.These functions are not built-in, meaning they belong to the
picklemodule. Therefore, before using them, you must import the module explicitly.Example:
Correct way to use:
import pickle data = {"name": "Riya", "age": 17} # Pickling (writing) with open("data.pkl", "wb") as f: pickle.dump(data, f) # Unpickling (reading) with open("data.pkl", "rb") as f: result = pickle.load(f) print(result)Incorrect way (without import):
pickle.dump(data, f)This will raise:
NameError: name 'pickle' is not definedBecause the module
picklewas never imported.Key Point:
Any function (dump()orload()) from a module must be used after importing that module.
For file handling with pickling, thepicklemodule is essential.
211. What does the file empfile.dat store in Program 2-8?
A. Text data of employees
B. Pickled Python list objects representing employee records
C. CSV formatted strings
D. JSON objects
Answer: B. Pickled Python list objects representing employee records
Explanation
Explanation:
Context from NCERT Program 2-8:
In Program 2-8 (from NCERT Class 12 Computer Science, Chapter 2: File Handling in Python), the fileempfile.datis used to store employee details such as employee number, name, basic pay, allowance, and total salary.The program uses the
pickle.dump()function to write each employee’s data into the file in binary format.
Each record is stored as a Python list object, for example:[eno, ename, ebasic, allow, totsal]These lists are pickled (serialized) before being written to the file, meaning that they are converted into a byte stream, not human-readable text.
Example (from Program 2-8):
import pickle f = open("empfile.dat", "wb") n = int(input("Enter number of employees: ")) for i in range(n): eno = int(input("Enter Employee Number: ")) ename = input("Enter Employee Name: ") ebasic = float(input("Enter Basic Salary: ")) allow = float(input("Enter Allowance: ")) totsal = ebasic + allow emp = [eno, ename, ebasic, allow, totsal] pickle.dump(emp, f) f.close()Here,
empfile.datcontains binary representations of these lists.
They can later be retrieved using:pickle.load(f)Key Points:
- The file
empfile.datis not a text file (so it can’t be opened in Notepad to view readable data).- It stores pickled list objects — i.e., serialized Python objects.
- To view the content properly, you must unpickle it using
pickle.load().
212. Which mode is used to append data to empfile.dat?
A. 'wb'
B. 'ab'
C. 'r+'
D. 'w+'
Answer: B. 'ab'
Explanation
Explanation:
When dealing with binary files in Python (such asempfile.datcreated using thepicklemodule), we use file modes that include a'b'to denote binary operations.
Mode Meaning Behavior 'wb'Write Binary Creates a new file or overwrites existing one. 'rb'Read Binary Reads an existing binary file. 'ab'Append Binary Adds data to the end of an existing binary file without erasing previous data. So, to add new employee records to an existing
empfile.datfile (without deleting old ones), we must open it in append binary mode ('ab').Example (from NCERT Program 2-9):
import pickle f = open("empfile.dat", "ab") # append binary mode n = int(input("Enter number of employees to add: ")) for i in range(n): eno = int(input("Enter Employee Number: ")) ename = input("Enter Employee Name: ") ebasic = float(input("Enter Basic Salary: ")) allow = float(input("Enter Allowance: ")) totsal = ebasic + allow emp = [eno, ename, ebasic, allow, totsal] pickle.dump(emp, f) f.close()In this code:
'ab'ensures new records are added at the end of the file.- It does not overwrite existing employee data.
Key Point:
'wb'→ Write Binary (creates a new file, erases old data)'ab'→ Append Binary (adds data to the end, keeps existing data)Hence,
'ab'is the correct mode when we want to append new pickled records.
213. How does the program determine the size of the binary file?
A. os.stat()
B. bfile.tell()
C. len()
D. By reading all records
Answer: B. Using bfile.tell()
Explanation
Explanation:
In Python’s file handling, every file object maintains an internal file pointer (also called the cursor).
- The function
tell()returns the current position (in bytes) of this pointer from the beginning of the file.- In a binary file, this position directly represents the number of bytes written or read.
Therefore, after writing data into the binary file, if we call:
bfile.tell()it will return the total size (in bytes) of the file up to that point.
Example (from NCERT Program 2-10):
import pickle bfile = open("empfile.dat", "rb+") bfile.seek(0, 2) # Move pointer to the end of file size = bfile.tell() # Get current position (file size) print("Size of file (in bytes):", size) bfile.close()Here’s what happens step-by-step:
- The file is opened in read+write binary mode (
'rb+').bfile.seek(0, 2)moves the pointer to the end of the file.bfile.tell()returns the current byte offset — which equals the total file size in bytes.Why not others?
os.stat()→ Can also give file size, but it’s not used in the NCERT program;tell()is preferred.len()→ Works for sequences (like lists or strings), not files.- Reading all records → Inefficient and not required;
tell()gives the size instantly.Key Point:
tell()is a built-in file method that returns the current byte position of the file pointer.
When called after writing or at the end of the file, it gives the total file size in bytes.
214. Which method is used to retrieve each employee record from the binary file?
A. read()
B. readline()
C. pickle.load()
D. loadlines()
Answer: C. pickle.load()
Explanation
Explanation:
Concept Overview:
When a Python object (like a list or dictionary) is pickled usingpickle.dump(), it is stored in a binary file as a sequence of bytes — not in human-readable form.
To retrieve that object back into memory, we must unpickle it usingpickle.load().
pickle.load(file)reads one complete serialized object from the file and deserializes it — that is, converts the stored byte stream back into the original Python object.Example (from NCERT Program 2-11):
import pickle f = open("empfile.dat", "rb") print("Employee Records:") while True: try: emp = pickle.load(f) # retrieves one record at a time print(emp) except EOFError: break f.close()Explanation of this program:
- The file
empfile.datcontains multiple employee records, each stored usingpickle.dump().- Each call to
pickle.load(f)reads one pickled record (a list), e.g.[eno, ename, ebasic, allow, totsal].- When the file ends, Python raises an
EOFError— signaling there are no more records to read.- The loop breaks at that point.
Why other options are incorrect:
read()→ Reads bytes or text data, not Python objects.readline()→ Reads one text line only (used in text files).loadlines()→ No such method exists in Python.Key Concept:
pickle.dump()→ Writes (pickles) Python object to binary file.pickle.load()→ Reads (unpickles) Python object from binary file.
215. What type of exception is handled when end of file is reached while reading records?
A. FileNotFoundError
B. EOFError
C. ValueError
D. IndexError
Answer: B. EOFError
Explanation
Explanation:
In Python, when you read data from a binary file using thepickle.load()function, it reads one serialized (pickled) object at a time.When all the pickled objects in the file have been successfully read, the file pointer reaches the end of file (EOF).
Ifpickle.load()is called again at this point, Python raises anEOFError— meaning “no more data to read.”This error must be handled using a
try–exceptblock to prevent program termination.Example (from NCERT Program 2-11):
import pickle f = open("empfile.dat", "rb") while True: try: emp = pickle.load(f) # Load next record print(emp) except EOFError: print("End of file reached.") break f.close()Step-by-step explanation:
pickle.load()reads one record (a list object) at a time.- After the last record, the next
load()call cannot find any more data.- Python raises
EOFError.- The
except EOFError:block catches this and stops further reading safely.Why other options are incorrect:
FileNotFoundError→ Raised if the file itself doesn’t exist when opening it.ValueError→ Raised for invalid conversions (likeint("abc")).IndexError→ Raised when accessing a list or tuple index that doesn’t exist.None of these occur during end-of-file reading in pickled files — only
EOFErrordoes.Key Point:
- When reading binary files with
pickle.load(), always use atry–except EOFErrorblock to handle the natural end of the file gracefully.
216. What happens if we open empfile.dat in text mode and try to read it?
A. Records are displayed correctly
B. Garbage characters appear
C. Python automatically converts binary to text
D. File is overwritten
Answer: B. Garbage characters appear
Explanation
Explanation:
The file empfile.dat in Program 2-8 is a binary file that stores employee data using the pickle module.
When a Python object (like a list containing employee details) is pickled, it is converted into a byte stream — a sequence of bytes that represents the internal structure of the object.If you try to open this binary file in text mode (
'r'or'rt') and useread()orreadline(), Python will attempt to interpret those bytes as normal characters (using a text encoding like UTF-8).
However, since most of those byte sequences do not correspond to valid characters, the result appears as unintelligible symbols or garbage characters on the screen.In simple terms, binary files are meant to be read only through binary or object-handling functions like:
pickle.load(bfile)and not through text-reading functions.
Opening it in text mode does not convert it automatically, nor does it overwrite the file — it just displays meaningless data.
Concept Summary:
File Type Mode Readable? Example Method Text File ‘r’ or ‘rt’ Yes (human-readable) read(),readline()Binary File ‘rb’ No (machine-readable) pickle.load()
217. What will happen if pickle.dump() is called with a non-serializable object?
A. Data is stored successfully
B. TypeError is raised
C. File becomes empty
D. Python converts object automatically
Answer: B. TypeError is raised
Explanation
Explanation:
Thepickle.dump()function is used to serialize Python objects — that is, to convert them into a byte stream that can be written into a binary file.
However, not every Python object can be serialized. Only picklable (serializable) objects — such aslist,dict,tuple,int,float,str, and user-defined classes (that follow pickle rules) — can be successfully dumped.If you try to serialize a non-serializable object, such as:
- open file handles,
- network connections (socket objects),
- lambda functions, or
- objects containing system-level resources,
then Python cannot represent them in a byte stream.
In such cases, the interpreter raises aTypeErrorindicating that the object type cannot be pickled.Example:
import pickle f = open("test.txt", "w") pickle.dump(f, open("data.dat", "wb")) # Raises TypeErrorThe above code fails because file objects (
_io.TextIOWrapper) are not serializable.Concept Summary:
Object Type Picklable? Example Built-in objects (list, dict, tuple, int, str) Yes pickle.dump([1,2,3], f)User-defined classes (without OS handles) Yes pickle.dump(obj, f)File objects, sockets, lambda, iterators No Raises TypeError
218. Which of the following is TRUE regarding Program 2-8?
A. Multiple employee records can be written without overwriting previous data
B. Each record must overwrite the previous one
C. File is automatically converted to text
D. Records cannot be read after writing
Answer: A. Multiple employee records can be written without overwriting previous data
Explanation
Explanation:
In Program 2-8, employee records are stored in a binary file namedempfile.datusing the pickle module.
The file is opened using the mode'ab', which stands for append + binary.When a file is opened in
'ab'mode:
- Existing data is preserved; nothing is deleted or replaced.
- New data is added at the end of the file.
- Data is written in binary format using
pickle.dump().This means that every time a new employee record (like
[eno, ename, ebasic, allow, totsal]) is dumped into the file, it is stored sequentially without affecting the earlier ones.
Later, the program can use a loop withpickle.load()repeatedly to read each stored record one by one untilEOFErroroccurs at the end of the file.Example concept:
import pickle with open("empfile.dat", "ab") as f: pickle.dump(["E101", "Ravi", 20000, 5000, 25000], f) pickle.dump(["E102", "Sita", 22000, 4000, 26000], f) # Both records stored safely without overwritingConcept Summary:
File Mode Description Effect 'wb'Write + Binary Overwrites file 'ab'Append + Binary Adds new data without overwriting 'rb'Read + Binary Reads binary data
219. What is the type of edata when reading records from the file?
A. String
B. List
C. Dictionary
D. Tuple
Answer: B. List
Explanation
Explanation:
In Program 2-8, every employee’s information — such as employee number, name, basic salary, allowances, and total salary — is grouped together and stored in a list before being written into the binary file.Example from the program:
edata = [eno, ename, ebasic, allow, totsal] pickle.dump(edata, empfile)Here,
edatais a list object that holds multiple data values of different types (string, integer, float).
When the record is later retrieved from the binary file using:edata = pickle.load(empfile)the same Python object that was originally stored (i.e., a list) is reconstructed (unpickled).
Therefore, the variableedataremains of type list after reading.So, when printed or processed, it looks something like:
['E101', 'Mohan', 20000, 5000, 25000]Concept Summary:
Stage Code Used Object Type of edataBefore writing edata = [eno, ename, ebasic, allow, totsal]List After reading edata = pickle.load(empfile)List Thus, unpickling restores the exact Python object type that was originally pickled.
220. Why is with open("empfile.dat","rb") as bfile: used for reading records?
A. Automatically closes the file after block
B. Converts binary to text
C. Reads all records in a single line
D. Appends new records
Answer: A. Automatically closes the file after block
Explanation
Explanation:
In Python, the statementwith open("empfile.dat", "rb") as bfile:is called a context manager statement.
It is the recommended way to open files — especially binary files — because it ensures that the file is automatically closed once the block of code inside thewithstatement finishes executing.When reading employee records from
empfile.dat, this structure ensures:
- The file is opened safely in binary read mode (
'rb').- It remains open only for the duration of the code block.
- Even if an exception (like
EOFError) occurs, Python automatically closes the file.This improves both data safety and code readability, and prevents resource leaks or file corruption.
Example:
import pickle with open("empfile.dat", "rb") as bfile: while True: try: edata = pickle.load(bfile) print(edata) except EOFError: break # No need to call bfile.close()Here, each record such as
['E101', 'Mohan', 20000, 5000, 25000]is read safely, and the file closes automatically after reading all records.Concept Summary:
Statement Purpose File Handling Behavior open()Opens a file Must close manually using .close()with open()Opens with context manager Automatically closes after block ends
221. What type of data is displayed when reading empfile.dat?
A. Strings
B. Lists
C. Dictionaries
D. Tuples
Answer: B. Lists
Explanation
Explanation:
The binary fileempfile.datin Program 2-8 stores each employee’s details using the pickle module.
When a record is written, it is stored as a Python list object that contains multiple data items such as employee number, name, basic salary, allowances, and total salary.For example:
edata = [eno, ename, ebasic, allow, totsal] pickle.dump(edata, empfile)When these records are later read using:
edata = pickle.load(empfile) print(edata)the unpickling process restores the same object that was originally stored.
Thus, the data displayed on the screen is a list — for example:['E101', 'Mohan', 20000, 5000, 25000]This list can then be accessed element by element, e.g.:
print(edata[1]) # Output: MohanSo, the type of data displayed is a list, not a string, tuple, or dictionary.
Concept Summary:
File Name Data Stored As Retrieved As Example Output empfile.dat List (Pickled) List (Unpickled) ['E101', 'Mohan', 20000, 5000, 25000]
222. What is the purpose of the try..except block in Program 2-8?
A. To catch syntax errors
B. To handle end-of-file (EOF) while reading records
C. To catch division errors
D. To close the file automatically
Answer: B. To handle end-of-file (EOF) while reading records
Explanation
Explanation:
In Program 2-8, thetry..exceptblock is used while reading employee records from the binary fileempfile.datusing thepickle.load()function.When reading data with
pickle.load(), Python continues to unpickle each stored object one by one until it reaches the end of the file.
After the last record is read, if the program tries to load another object beyond that point, Python raises anEOFError(End Of File Error).To prevent the program from crashing, this error is caught using an
exceptblock.
This allows the loop to exit gracefully when all records have been successfully read.Example:
import pickle with open("empfile.dat", "rb") as bfile: while True: try: edata = pickle.load(bfile) print(edata) except EOFError: breakHere, the
tryblock continuously loads data until the file ends, and theexcept EOFErrorblock safely breaks out of the loop without causing an error.Concept Summary:
Exception Meaning When Raised Handled In EOFErrorEnd of File Error When pickle.load()tries to read beyond the endexcept EOFError:block
223. Which mode is used to write employee records in Program 2-8?
A. 'wb'
B. 'ab'
C. 'rb'
D. 'r+'
Answer: B. 'ab'
Explanation
Explanation:
In Program 2-8, employee data is written into a binary file namedempfile.datusing the append binary mode ('ab').When a file is opened in
'ab'mode:
'a'stands for append, which means new data will be added at the end of the file.'b'stands for binary, which means the file will store byte stream data, not text.Therefore,
'ab'mode allows the program to add multiple employee records without deleting or overwriting any existing data.
This is very useful when new employee entries need to be saved while keeping the old ones safe.Example:
import pickle with open("empfile.dat", "ab") as f: edata = ['E103', 'Mohan', 22000, 4000, 26000] pickle.dump(edata, f)Here, the record is appended at the end of the file. If the file already contains previous records, they remain intact.
Concept Summary:
Mode Meaning Function 'wb'Write + Binary Overwrites the file 'ab'Append + Binary Adds new data without overwriting 'rb'Read + Binary Reads binary data 'r+'Read and Write For text files, not binary append
224. What does bfile.tell() return in the program?
A. Number of records
B. Current byte position in the file
C. File name
D. Total number of characters in text
Answer: B. Current byte position in the file
Explanation
Explanation:
tell()method returns the current position of the file pointer in bytes from the beginning of the file.
When working with binary files (likeempfile.dat), it shows how far the file pointer has moved — effectively indicating how many bytes have been read or written so far.For example:
bfile = open("empfile.dat", "ab") pickle.dump(["Mohan", 102, 50000], bfile) print(bfile.tell())This prints the byte position after writing the record.
225. What will happen if empfile.dat is opened in text mode ('r') instead of binary mode ('rb')?
A. Data will be displayed correctly
B. Garbage values will appear
C. Python will automatically convert it to binary
D. File will be erased
Answer: B. Garbage values will appear
Explanation
Explanation:
empfile.datis a binary file created using thepicklemodule, which stores data in byte (binary) format — not in plain text.If you open this file in text mode (‘r’), Python will try to interpret those binary bytes as text characters. Since many byte values don’t correspond to readable text characters, the result will appear as garbage or unintelligible symbols on the screen.
To correctly read binary data, the file must be opened in binary mode (‘rb’), which ensures that the bytes are read exactly as they were written — allowing
pickle.load()to reconstruct the original Python objects.Example:
# Incorrect (text mode) with open("empfile.dat", "r") as f: print(f.read()) # Garbage output # Correct (binary mode) import pickle with open("empfile.dat", "rb") as f: data = pickle.load(f) print(data) # Proper list or record displayed
226. Which method is used to store an object in a binary file?
A. write()
B. writelines()
C. pickle.dump()
D. pickle.load()
Answer: C. pickle.dump()
Explanation
Explanation:
In Python, thepicklemodule is used for object serialization, meaning converting a Python object (like list, dictionary, or tuple) into a byte stream that can be stored in a binary file.The method
pickle.dump(object, file)writes (or dumps) this serialized form of the object into the specified binary file. Later, the same object can be retrieved usingpickle.load(file)during unpickling.
write()andwritelines()are used for text files, not binary files — they handle strings, not serialized byte streams.Example:
import pickle employee = ["Mohan", 101, 45000] with open("empfile.dat", "wb") as f: pickle.dump(employee, f) # Object stored in binary format
227. Which method is used to retrieve an object from a binary file?
A. read()
B. readline()
C. pickle.load()
D. loadlines()
Answer: C. pickle.load()
Explanation
Explanation:
When data is stored in a binary file usingpickle.dump(), it is saved in a serialized (byte stream) form. To retrieve and restore that original Python object, the methodpickle.load(file)is used.This process is known as deserialization or unpickling. The
load()function reads the next pickled object from the file and reconstructs it back into its original Python structure such as a list, dictionary, or tuple.In contrast,
read()andreadline()are meant for text files, not binary files, andloadlines()does not exist in Python.Example:
import pickle with open("empfile.dat", "rb") as f: employee = pickle.load(f) print(employee) # Output: ['Mohan', 101, 45000]
228. What happens if a non-serializable object is passed to pickle.dump()?
A. It is stored as a string
B. Python raises a TypeError
C. File is automatically converted to text
D. Object is ignored
Answer: B. Python raises a TypeError
Explanation
Explanation:
Thepicklemodule in Python can only serialize (or pickle) specific data types — such as lists, dictionaries, tuples, sets, and most user-defined classes.
However, if you try to pickle objects that cannot be represented as byte streams — for example, open file objects, sockets, iterators, or lambda functions — Python raises aTypeError.This ensures data integrity and prevents corruption in the binary file.
Example:
import pickle f = open("test.txt", "w") # file objects are not serializable try: pickle.dump(f, open("data.dat", "wb")) except TypeError as e: print("Error:", e)Output:
Error: cannot pickle '_io.TextIOWrapper' object
229. What is the total salary of Employee No. 2 in the output?
A. 38250
B. 5300
C. 43550
D. 37000
Answer: C. 43550
Explanation
Explanation:
In Program 2-8 (from NCERT Class 12 Computer Science, Chapter 2 – File Handling in Python), each employee record includes:[Employee Number, Employee Name, Basic Salary, Allowances, Total Salary].The total salary is calculated as: Total Salary=Basic Salary+Allowances\text{Total Salary} = \text{Basic Salary} + \text{Allowances}Total Salary=Basic Salary+Allowances
For Employee No. 2,
- Basic Salary = 38250
- Allowances = 5300
Hence, 43550=38250+530043550 = 38250 + 530043550=38250+5300
The calculated total is 43550, which matches the program output.
230. What type of file is empfile.dat?
A. Text file
B. Binary file
C. CSV file
D. JSON file
Answer: B. Binary file
Explanation
Explanation:
The fileempfile.datis created and accessed using modes like'wb','rb', and'ab', which denote write, read, and append in binary mode.
This file stores Python objects that have been serialized (pickled) using thepickle.dump()function.Since the data is stored as a byte stream, it is not human-readable — unlike text, CSV, or JSON files. To read it correctly, we must use
pickle.load(), which performs deserialization (unpickling) and restores the original Python objects.Example:
import pickle # Writing (pickling) with open("empfile.dat", "wb") as f: pickle.dump(["Mohan", 102, 42000, 5000, 47000], f) # Reading (unpickling) with open("empfile.dat", "rb") as f: data = pickle.load(f) print(data)Output:
['Mohan', 102, 42000, 5000, 47000]
231. Which of the following extensions represents a text file in Python?
A. .txt
B. .exe
C. .mp3
D. .jpg
Answer: A. .txt
Explanation
Explanation:
A text file in Python is one that stores human-readable data — that is, characters like letters, digits, punctuation, and whitespace — encoded in a standard text encoding such as UTF-8 or ASCII.Files with extensions like .txt, .py, .csv, .html, or .c are examples of text files because their content can be opened and understood using a simple text editor such as Notepad or VS Code.
Other extensions like .exe, .mp3, or .jpg represent binary files, which store data in machine-readable form (not meant for direct reading).
Example:
# Writing to a text file with open("notes.txt", "w") as f: f.write("This is a text file in Python.")
232. Each line of a text file is terminated by a special character called:
A. EOF
B. EOL
C. ESC
D. NULL
Answer: B. EOL
Explanation
Explanation:
In a text file, each line is separated by a special marker known as the End of Line (EOL) character. It tells Python and the operating system where one line ends and the next begins.In Python, this character is represented by the newline symbol
\n, which is automatically inserted when you use statements likeprint()orwrite()with a newline.When Python writes to or reads from a text file in text mode (
't'), it handles this EOL character according to the operating system:
- On Windows, EOL is represented as
\r\n(Carriage Return + Line Feed).- On Linux and macOS, it is represented simply as
\n(Line Feed).The EOL marker ensures that when the file is opened in a text editor, each line starts from a new line rather than appearing continuously.
Characters like EOF (End of File) mark the end of the entire file, not a line; ESC represents the escape key or escape sequence indicator; and NULL (
\0) denotes a zero byte used in low-level programming but not for line termination in text files.Example:
with open("demo.txt", "w") as f: f.write("Mohan\n") f.write("Kewat\n") with open("demo.txt", "r") as f: for line in f: print(repr(line))Output:
'Mohan\n' 'Kewat\n'Here,
\nis the EOL character marking the end of each line.“Each line in a text file is terminated by an end-of-line (EOL) character, generally represented as\n.”
233. Binary files are stored as:
A. ASCII characters
B. Human-readable text
C. A stream of bytes
D. Unicode strings
Answer: C. A stream of bytes
Explanation
Explanation:
A binary file stores data in the form of a continuous stream of bytes, which represents the exact memory format of data objects. Unlike text files, binary files are not human-readable — they can only be interpreted correctly by programs that know how the data was encoded.Binary files are commonly used for storing images, audio, videos, and pickled Python objects because these data types contain raw byte-level information that cannot be represented as simple text.
When working with binary files in Python, we open them in binary modes such as
'rb'(read binary),'wb'(write binary), or'ab'(append binary). Functions likepickle.dump()andpickle.load()are specifically designed to handle binary data streams.Characters such as ASCII or Unicode are used in text files, not in binary files. Binary files deal purely with bytes — each byte may represent part of a number, pixel, or encoded object.
Example:
# Writing binary data with open("data.dat", "wb") as f: f.write(b'\x41\x42\x43') # Writing bytes for A, B, C # Reading binary data with open("data.dat", "rb") as f: content = f.read() print(content)Output:
b'ABC'Here, the file stores data as a sequence of bytes (b’ABC’), not as human-readable text.
“Binary files store data in the same format as it is represented in computer memory, i.e., as a stream of bytes.”
234. Which Python function is used to open a file?
A. openfile()
B. open()
C. file_open()
D. fopen()
Answer: B. open()
Explanation
Explanation:
In Python, theopen()function is the built-in method used to open a file and return a file object (also known as a file handle). This file object allows you to perform operations such as reading, writing, or appending data to the file.The general syntax is:
file_object = open(filename, mode)Here:
filename→ The name (and path, if needed) of the file to open.mode→ Specifies the purpose for which the file is opened, such as:
'r'→ read (default)'w'→ write'a'→ append'b'→ binary mode't'→ text mode (default)After completing the operation, the file must be closed using the
close()method to release system resources.Example:
# Opening a file in write mode f = open("myfile.txt", "w") f.write("Hello, World!") f.close()Explanation:
open("myfile.txt", "w")opens the filemyfile.txtfor writing.- If the file doesn’t exist, it will be created automatically.
- After writing,
f.close()closes the file safely.“A file is opened using the built-in open() function, which returns a file object.”
235. What happens when close() method is called on a file object?
A. Only the file pointer moves to beginning
B. File content is erased
C. Resources like memory and processor allocated to file are freed
D. Nothing happens
Answer: C. Resources like memory and processor allocated to file are freed
Explanation
Explanation:
When you call theclose()method on a file object in Python, it performs two main functions:
- Flushes the Buffer:
Any data that is still in the memory buffer (not yet written to the file on disk) is immediately written (flushed) to the file.- Releases System Resources:
The memory, processor, and file handle resources that were being used by the open file are freed and made available for other processes.Once a file is closed, any attempt to perform read or write operations on it will raise a
ValueError(e.g., “I/O operation on closed file”).Example:
f = open("data.txt", "w") f.write("Python File Handling") f.close() # Trying to write after closing will raise an error f.write("This will cause an error") # ValueErrorExplanation:
f.close()flushes the buffer and releases system resources.- Any subsequent operation (like write/read) will not be allowed on a closed file.
“The close() function closes the file and frees up the resources used by it.”
“Flush and close this stream. Once the stream is closed, further I/O operations will raise a ValueError.”
236. Which method is used to write a single string to a file?
A. writelines()
B. write()
C. read()
D. readline()
Answer: B. write()
Explanation
Explanation:
Thewrite()method in Python is used to write a single string into a file.
It does not automatically add a newline (\n) at the end — if you want the next text on a new line, you must include\nmanually.Example:
f = open("example.txt", "w") f.write("Hello, World!\n") f.write("This is a new line.") f.close()Explanation:
write()writes exactly what you provide inside the parentheses.- In the above example, the first line ends with
\n, so the second line appears on a new line in the file.- If you omit
\n, all text will appear in a single continuous line.Why the others are not correct:
writelines()→ used to write a list of strings, not a single string.read()→ used for reading file content.readline()→ reads only one line from a text file.“The write() function is used to write a single string to a file.”
“Write the given string to the stream and return the number of characters written.”
237. Which method is used to write multiple strings to a file at once?
A. write()
B. writelines()
C. readlines()
D. append()
Answer: B. writelines()
Explanation
Explanation:
Thewritelines()method in Python is used to write multiple strings to a file simultaneously.
It accepts an iterable (like a list or tuple) containing string elements and writes them sequentially to the file without automatically adding newline characters (\n).Example:
lines = ["Hello everyone\n", "Welcome to File Handling\n", "This is Python\n"] f = open("example.txt", "w") f.writelines(lines) f.close()Explanation:
- Each element of the list
linesis written to the file in order.- Since each string already contains
\n, every line appears separately.- If
\nis not included, all lines will appear together on a single line.Why the others are not correct:
write()→ writes only one string at a time, not multiple.readlines()→ used for reading all lines from a file into a list.append()→ is a file mode, not a method; it is used to open a file for adding new content at the end.“The writelines() function writes a list or tuple of strings to a text file.”
“Write a list of strings to the stream. Line separators are not added automatically.”
238. The read([n]) method in Python:
A. Reads all lines as a list
B. Reads a complete line including newline
C. Reads a specified number of bytes
D. Writes data to file
Answer: C. Reads a specified number of bytes
Explanation
Explanation:
Theread([n])method is used to read data from a file.
- When you specify a number
n, it reads exactlynbytes (or characters) from the file.- If
nis omitted or negative, the method reads the entire file content.- After each
read()call, the file pointer moves ahead by the number of bytes read.Example:
f = open("data.txt", "r") text = f.read(10) # Reads first 10 characters print(text) f.close()If
data.txtcontains"Python file handling is easy",
the output will be:Python filHere only the first 10 characters are read.
Clarifications:
readlines()→ returns all lines as a list.readline()→ reads one line (until\n).read()→ reads characters or bytes, depending on mode.write()→ used for writing, not reading.
239. The difference between readline([n]) and readlines() is:
A. readline() reads multiple lines at once, readlines() reads single line
B. readline() reads a single line, readlines() reads all lines as a list
C. Both read all lines but return different formats
D. None of the above
Answer: B. readline() reads a single line, readlines() reads all lines as a list
Explanation
Explanation:
Bothreadline()andreadlines()are used for reading data from a text file, but they differ in how much data they read and what they return:
readline([n])→
Reads only one line from the file (ending with\n).
Ifnis specified, it reads up to n characters of that line.
Each call toreadline()moves the file pointer to the next line.readlines()→
Reads all lines from the file and returns them as a list of strings, where each element represents one line including the newline character\n.Example:
Supposenotes.txtcontains:Python File Handling Chapter 2f = open("notes.txt", "r") print(f.readline()) # Output: Python\n print(f.readlines()) # Output: ['File Handling\n', 'Chapter 2'] f.close()Key Points:
readline()→ reads one line at a time → string output.readlines()→ reads all remaining lines → list output.- Both maintain the file pointer position, so repeated calls continue reading where the last left off.
“readline() reads a single line from the file whereas readlines() reads all lines and returns a list.”
240. What does the tell() method return in Python file handling?
A. File size in bytes
B. Current position of the file pointer in bytes
C. Number of lines in the file
D. Total characters in file
Answer: B. Current position of the file pointer in bytes
Explanation
Explanation:
In Python, every open file has a file pointer (cursor) that keeps track of where the next read or write operation will occur.The
tell()method returns the current position (in bytes) of this file pointer from the beginning of the file.It is useful for monitoring or controlling the reading and writing process, especially in binary files or when combined with the
seek()method.Example:
f = open("data.txt", "r") print(f.tell()) # Output: 0 (pointer at start) f.read(5) print(f.tell()) # Output: 5 (pointer moved 5 bytes ahead) f.close()Here,
- Initially, the file pointer is at position 0.
- After reading 5 characters,
tell()returns 5, indicating the pointer has advanced 5 bytes.Key Points:
- Works for both text and binary files.
tell()gives the byte offset, not character count.- Commonly used with
seek()to navigate inside a file.“The tell() method returns the current position of the file pointer (in bytes) from the beginning of the file.”
241. What is the use of seek(offset, reference_point) method?
A. To close the file
B. To move the file pointer to a specific position
C. To read all lines
D. To delete file contents
Answer: B. To move the file pointer to a specific position
Explanation
Explanation:
Theseek(offset, reference_point)method in Python is used to move (reposition) the file pointer to a specific location within the file.
This allows reading or writing from a desired position instead of sequentially processing the entire file.
offset→ The number of bytes to move.reference_point→ The position from where the offset is calculated:
0→ Beginning of the file (default)1→ Current position of the file pointer2→ End of the fileExample:
f = open("example.txt", "r") f.seek(5, 0) # Moves pointer 5 bytes from beginning print(f.tell()) # Output: 5 f.close()Here,
- The pointer moves 5 bytes ahead from the start of the file.
- You can later use
read()to start reading from that specific position.Key Points:
seek()is mainly used in binary files or for random access within a file.- It works together with
tell()to navigate efficiently.- In text files, only
seek(0)(reset to start) is consistently reliable due to encoding variations.“seek(offset, reference_point) method repositions the file pointer to a specified location in the file.”
Computer Science Class XII NCERT book [Download]
Class 12 Computer Science MCQs [link]
Keep Learning, Keep Growing with Mohan Exam
At Mohan Exam, we believe that learning is not just about memorizing answers — it’s about understanding concepts deeply and applying them with confidence.
Your journey toward success starts with curiosity, consistency, and the right guidance — and we’re here to provide all three.
Because when you learn better, you grow stronger, and achieve greater heights.
So, keep exploring… keep practicing… and keep shining with Mohan Exam — where learning meets excellence!
