1. LPU MCA Semester 1
  2. CAB106
  3. 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.

ModeMeaning
rRead (default); error if the file is missing
wWrite; erases existing contents
aAppend to the end
xCreate; fails if it already exists
bBinary, 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

Question 1 · Tier 1, Recall

Which file mode opens a file for writing and erases its previous contents?

  1. w
  2. r
  3. a
  4. 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.

Question 2 · Tier 1, Recall

Which file mode adds new text at the end of an existing file without erasing it?

  1. a
  2. w
  3. r
  4. 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.