Consider the statement given below :
``python
f1 = open("pqr.dat","__")
``
Which of the following is the correct file mode to open the file in read only mode ?
Consider the statement given below :
``python
f1 = open("pqr.dat","__")
``
Which of the following is the correct file mode to open the file in read only mode ?
Options
Correct option: (B) rb
Since pqr.dat is a binary data file, it must be opened in binary mode; rb opens the file strictly for reading in binary mode, which is the correct read-only mode.
Marking Scheme
- 11 mark: correct option (B) rb selected.
Hint
Match the file mode to two things: text vs binary content, and whether writing should be possible.
Quick Oral Answer
rb opens a binary file strictly for reading; unlike r+ or rb+, it does not permit writing, making it the true read-only mode for a .dat file.
Analysis & Explanation
File mode selection depends on both the intended operation (read/write) and the file's nature (text/binary).
Why (B) is correct
- A
.datfile conventionally stores binary data (such as pickled Python objects), so it should be opened in binary mode. rbstands for 'read binary' — it opens the file only for reading; if the file does not exist, Python raises aFileNotFoundErrorinstead of creating one, confirming it is read-only.
Why the other options are wrong
- (A)
aopens the file for appending (writing at the end); it is not a read mode at all. - (C)
r+opens the file for both reading and writing in text mode — it is not read-only. - (D)
rb+opens the file for both reading and writing in binary mode — liker+, it allows writing, so it is not read-only.
Common Mistakes
- 1Choosing r+ or rb+ thinking they are 'safer' read modes, without realizing the '+' allows writing too.
- 2Forgetting that a .dat file needs binary mode (rb) rather than plain text mode (r).
Interesting Facts
Python's open() defaults to text mode ('rt') if no mode is specified, but binary files like .dat, images, or pickled objects must always be opened with a 'b' flag to avoid data corruption.
Opening a non-existent file in 'r' or 'rb' mode raises a FileNotFoundError, while 'a' or 'w' modes silently create the file if it doesn't exist.
Spotted a mistake or something unclear?
Tell us — we fix reported answers fast.
Frequently Asked Questions
Why is 'r' not one of the options if it means read-only?
'r' is the default text-mode read-only flag, but since pqr.dat is a binary data file, plain text mode 'r' would misinterpret its bytes; the paper instead tests recognition that binary files need 'rb', the binary equivalent of read-only mode.
What is the difference between r+ and rb+?
r+ opens a file for both reading and writing in text mode, while rb+ does the same in binary mode. Both allow writing, so neither is a strictly read-only mode, unlike rb.