Files and modules
A file object is stateful — a mode and a cursor — and modules turn programs into importable, reusable files.
Data that lives only in memory disappears when the program ends. Files are how a program remembers across runs, and they come with a small but sharp-edged model: every open file has a mode and a cursor, and both change what the next operation is allowed to do.
A file object is a bookmark in a book
The mode says whether you may read or write at all; the cursor is where your
bookmark sits. Reading advances the bookmark, writing overwrites from the
bookmark onward, and seeking moves it. Opening with w also begins by
tearing out every existing page.
Open a file below in different modes, then write, read and seek. Illegal operations raise the same kind of error Python would.
Open in a mode, then read and write — the cursor shows where the file object is
▏call log
—
A file object is stateful: it remembers the mode and the cursor. Opening with w wipes the file before anything is written, a always moves the cursor to the end, and reading only works in a mode that permits it — the same text produces different results depending on how the file was opened.
Modes and the cursor
"r"opens for reading. The file must exist. This is the default."w"opens for writing and truncates the file to empty first."a"opens for appending; writes go to the end regardless of the cursor."b"adds binary mode, giving youbytesinstead ofstr.
read() consumes from the cursor to the end and leaves the cursor at the end;
calling it again returns "". readline() reads one line, readlines() reads
them all. seek(0) rewinds so the data can be read again.
with open("notes.txt", "w") as f:
f.write("hello\n")
with open("notes.txt", "a") as f:
f.write("world\n")
with open("notes.txt") as f:
print(f.read()) # hello\nworld\nw is destructive before you write anything
open("data.txt", "w") empties the file the instant it is called, even if
nothing is written afterwards. To add data, use "a"; to rewrite safely,
write to a temporary file and rename it over the original when finished.
Text, encoding and line endings
Text files are decoded using an encoding, UTF-8 by default on modern Python.
Always pass encoding="utf-8" explicitly when the file may contain non-ASCII
text, so the program does not depend on the machine's locale. Reading in binary
mode skips decoding and gives you raw bytes.
Modules: programs that can be imported
A module is just a .py file. import math runs math.py once, creates a
module object, and binds the name math to it; from math import sqrt binds
the function directly. The first import is the expensive one — later imports
reuse the cached module, which is why module-level state is shared.
The __name__ variable is "__main__" only for the file you ran directly:
def main():
...
if __name__ == "__main__":
main()That guard lets a file behave as a program when run and as a library when imported, without executing its top-level work during the import.
Illustrative vs real
The panel keeps the whole file in memory as a string, so the cursor is a
number you can see. Real files live on a disk, may be larger than memory, and
buffering means data is flushed in chunks. The mode and cursor rules — and the
destructiveness of w — are exactly the same.
Check yourself
Eduspheria wiki · Programming & Data Structures, Objects and I/O
0 / 5 answered
From the assignment paper
Modeled on NITJ AI-503, Assignment/Quiz
0 / 6 answered
Where next: data structures — starting with the array that every stack and queue is built on.