Lesson 38 of 55
9 mins readPython File I/O: Reading & Writing Files
In Plain English
Manage filesystem operations with open() do-blocks that guarantee automatic file closing upon block completion. Read full files, lines, or streams.
Deep Dive: How It Works
Safe open() Do-Block: open("filename.txt", "w") do f ... end ensures the file descriptor is closed even if an error is thrown.
Reading Lines: readline(f) reads one line; eachline("file.txt") lazily yields lines one at a time without loading the whole file into RAM.
Writing Data: write(f, "text") writes raw strings or bytes; println(f, "line") writes text followed by newline.
Core Rules to Remember

open() Do-Block Guarantees: Auto-closes file handles safely to avoid resource leaks.

eachline() Lazy Streaming: Process multi-gigabyte dataset files line-by-line in constant memory.
Live Interactive Example
Hit Run Code to see it liveWriting and Reading Files with IO Streams
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
Output Console
Click "Run Code" to view the rendered output.
How it works: IOBuffer behaves like a regular file stream; eachline streams lines efficiently.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Stream String with IOBuffer
Create `buf = IOBuffer()`.
Write `println(buf, "ZenCompiler Julia Runner")`.
Seek to start with `seekstart(buf)` and print the line with `readline(buf)`.
1
2
3
4
5
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.