Functions & Files · Unit 4

File Handling

Open, read, write and append files

Unit 4 · Files in the browser

A file is a stream of text, opened with a mode

Programs use files to keep information between runs. This learning lab uses Pyodide’s in-memory virtual filesystem; code runs in your browser and does not read or write your device’s files. The shared runtime includes a sample class_notes.txt.

Virtual file · class_notes.txt

Mira's class notes
Python practice: variables, lists, and loops.

The sample is seeded once in the shared browser runtime.

Use the context manager pattern

with open(path, mode, encoding="utf-8") as file:
    data = file.read()

The with block closes the file even if an error occurs. Choose an encoding for predictable text handling.

Explore each file operation

Choose a task. Run the real Python code and compare its output with the description.

read()

Reads the remaining contents as one string. A file pointer moves as data is read.

Mode guide
  • r reads an existing file.
  • w writes from the beginning and truncates existing contents.
  • a writes at the end, preserving what is already there.

Try changing read() to readline(), or remove \\n from a row in the writelines example to observe the difference.

Read all
Starting up Python…
with open("class_notes.txt", "r", encoding="utf-8") as file:
    contents = file.read()
print(contents)
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Read patterns without losing track of the file position

After a read, the file cursor advances. If you call read() again immediately, it may return an empty string because the cursor is already at the end. Reopen the file or use seek(0) when you intentionally need to start again.

Observe the file cursor
Starting up Python…
with open("class_notes.txt", "r", encoding="utf-8") as file:
    print("First read:", repr(file.readline()))
    print("Second read:", repr(file.read()))
    print("At end:", repr(file.read()))
    file.seek(0)
    print("After seek:", repr(file.readline()))
The editor is ready while Python loads in the background.

Output

Your program's output will appear here.
Common Python mistakes

NameError: name 'mark' is not defined

NameError: A name was used before Python could find a variable or function with that name.

IndexError: list index out of range

IndexError: The requested position is outside the items in this list or sequence.

KeyError: 'email'

KeyError: That key does not exist in this dictionary.

TypeError: can only concatenate str (not "int") to str

TypeError: This operation does not work with the kind of value it received.

ZeroDivisionError: division by zero

ZeroDivisionError: A number cannot be divided by zero.

SyntaxError: invalid syntax

SyntaxError: Python could not understand the structure of this line. Check spelling, brackets, colons, and quotes.

IndentationError: expected an indented block

IndentationError: The spaces at the start of a line do not match Python's block structure.

Common file-handling mistakes

FileNotFoundError

Opening a missing path in r mode

Read mode expects the file to exist. Use a known sample path or create the file first.

Overwriting data

Opening an existing file with w

w truncates the file. Choose a mode deliberately; use a for append.

Lines run together

writelines(rows) without newline characters

writelines writes the strings exactly as provided. Include \n where each line should end.

Reading twice

Calling read() twice on one open handle

The cursor advances. Reopen the file or seek back to the start.

Check your understanding

1. Which mode adds text at the end without deleting current contents?

2. Does writelines() add line breaks between strings?

3. Why use with open(...) as file?