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 overfyields 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 maththenmath.sqrt(9);from math import sqrtthensqrt(9);import numpy as npaliases. Importing executes the module's top-level code once, then caches it insys.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)raisesTypeError; convert withstr(5).- Reading twice returns
""the second time because the position is at end-of-file; usef.seek(0)to rewind. from math import *pollutes the namespace and can hide names.- Importing a missing module raises
ModuleNotFoundError.