Lesson 51 of 55
9 mins readPython File I/O: io.open, io.read & io.write
In Plain English
The `io` library provides complete file management: `io.open(filename, mode)` returns file handles for streaming lines with `file:read("*l")` and writing with `file:write()`.
Deep Dive: How It Works
File Modes: `"r"` (read), `"w"` (write/truncate), `"a"` (append), `"r+"` (read/write).
file:read("*l"): Reads a single line stripping newline.
file:read("*a"): Reads the entire file content as a single string.
io.lines(path): Returns an iterator reading file line-by-line.
Core Rules to Remember

Explicit file:close(): Always close file handles when finished to free operating system descriptors.

io.lines() Iterator: Cleanest memory-efficient way to stream large files.
Live Interactive Example
Hit Run Code to see it liveSimulating Stream Processing with String Buffers
Python 3.12
1
2
3
4
5
6
7
8
9
10
11
Output Console
Click "Run Code" to view the rendered output.
How it works: Simulated stream reading line-by-line with formatted line numbering.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Count Stream Records
Given `local data = "A
B
C
"`.
Count total lines using `for line in data:gmatch("([^
]+)") do count = count + 1 end`.
Print `"Total lines: " .. count`.
1
2
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.