- LPU MCA Semester 1
- CAB106
- Unit 5
CAB106 · Unit 5: Exception handling and file management
File handling: reading and writing files
13 practice questions
Key points
- Use with so the file closes automatically
- r, w, a and x modes behave differently
- read, readline, readlines and iteration return different shapes
- A file keeps a position; seek and tell move and read it
Files are opened with open(name, mode), and the with statement closes them automatically, so f.closed is True after the block.
| Mode | Meaning |
|---|---|
r | Read (default); error if the file is missing |
w | Write; erases existing contents |
a | Append to the end |
x | Create; fails if it already exists |
b | Binary, added to another mode (rb, wb) |
+ | Read and write |
Reading methods: read() returns all the text, readline() returns one line including its newline, readlines() returns a list of lines, and iterating over the file yields lines one at a time (use line.strip() to remove the newline). The file keeps a position, so a second read() returns an empty string; seek(n) moves it and tell() reports it. Binary mode works with bytes objects such as b'AB'.
Opening a missing file for reading raises FileNotFoundError; opening an existing file with x raises FileExistsError.
Exam trap: mode w destroys the old contents the moment the file is opened, even if nothing is written. Use a to add to a file.
Try two questions
Which file mode opens a file for writing and erases its previous contents?
- w
- r
- a
- x
Show the answer
A. Mode w truncates an existing file, or creates it if it does not exist.
Why not B: r opens a file for reading only.
Why not C: a keeps the old contents and adds new text at the end.
Why not D: x creates a new file and fails if it already exists.
Which file mode adds new text at the end of an existing file without erasing it?
- a
- w
- r
- x
Show the answer
A. Mode a is append mode: writes go to the end and old content is kept.
Why not B: w erases the old contents first.
Why not C: r opens the file for reading only.
Why not D: x only creates a new file and fails if it already exists.