PCEP study materials
PCEP study resources

PCEP: File Handling and Module Imports

PCEP · Work through your exam, one topic at a time.

All guide sections

File Handling and Module Imports

What this domain covers

The smallest PCEP domain covers opening, reading and writing text files, and importing modules from the standard library.

Core rules

  • open(path, mode) returns a file object. Modes: "r" read (default, file must exist), "w" write (creates or truncates), "a" append, "r+" read/write, plus "b" for binary and "t" for text.
  • Use a context manager: with open("data.txt") as f: closes the file automatically, even if an exception occurs.
  • Reading: f.read() returns the whole file as one string; f.readline() returns one line including \n; f.readlines() returns a list of lines. Iterating over f yields lines.
  • Writing: f.write(s) writes a string and returns the character count; f.writelines(seq) writes an iterable of strings. No newline is added automatically.
  • Import forms: import math then math.sqrt(9); from math import sqrt then sqrt(9); import numpy as np aliases. Importing executes the module's top-level code once, then caches it in sys.modules.

Worked example

with open("out.txt", "w") as f: f.write("a\nb") with open("out.txt") as f: print(f.read().splitlines()) Output: ['a', 'b']. The first with creates or truncates the file and writes two lines; the second opens for reading and read() returns "a\nb", which splitlines() turns into a list.

Traps

  • "w" erases existing content; use "a" to preserve it.
  • f.write(5) raises TypeError; convert with str(5).
  • Reading twice returns "" the second time because the position is at end-of-file; use f.seek(0) to rewind.
  • from math import * pollutes the namespace and can hide names.
  • Importing a missing module raises ModuleNotFoundError.