Wiki
Core12 min read

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

closedcursor at 0
▏

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 you bytes instead of str.

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\n

w 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

  1. 1Which mode empties an existing file as soon as it is opened?
    Multiple choice
  2. 2In append mode, the cursor position determines where new text is inserted.
    True / false
  3. 3Which statement guarantees a file is closed when its block exits, even on an error?
    Short answer
  4. 4When a file is imported rather than run directly, what is __name__?
    Multiple choice
  5. 5After reading a file to the end, how many characters does a second read() with no arguments return?
    characters
    Numeric answer

From the assignment paper

Modeled on NITJ AI-503, Assignment/Quiz

0 / 6 answered

  1. 1Which mode opens an existing file so that new writes are added at the end without erasing what is already there?
    Multiple choice
  2. 2What does the readlines() method return?
    Multiple choice
  3. 3What is the purpose of the seek() method?
    Multiple choice
  4. 4A program calls open("report.txt", "w") with no directory in the name. Where is the file created?
    Multiple choice
  5. 5A file's contents survive after the program ends because files are held in secondary storage.
    True / false
  6. 6Which standard-library module saves and reloads whole Python objects in a binary file?
    Short answer

Where next: data structures — starting with the array that every stack and queue is built on.