Lesson 44 of 55
9 mins readPython File I/O: Reading & Writing Files
In Plain English
Manage files using high-level standard prelude functions: readFile (lazy file reading), writeFile (create/overwrite), and appendFile (append data).
Deep Dive: How It Works
readFile: Lazily reads file contents as a String.
writeFile: Writes a String to a file, creating or overwriting it.
withFile: System.IO.withFile ensures the file handle is closed safely even in the event of an exception.
Core Rules to Remember

Simple File Primitives: readFile and writeFile handle common text file tasks in one line.

withFile Safety: Guarantees automatic file handle closing.
Live Interactive Example
Hit Run Code to see it liveString Processing over Text Streams
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: lines splits string by newlines; unlines rejoins them.
Your Turn: Micro Challenge
No pressure! Edit the starter code below and test your solution with instant feedback.
Micro Exercise
Count Lines in Text
Count the lines in `"Alpha\nBeta\nGamma"` using `length . lines`.
Print `"Line count: "` followed by the result.
1
2
3
4
5
6
Sandbox Output
Click "Run & Check" to test your solution.
Finished reading and practicing?
Mark this lesson as completed to update your course progress.