Reading and Writing Text Files
- Module 8, lesson 1
- About 9 minutes
- Builds on earlier lessons
- 12-question quiz at the end
What you will learn
- Pick a mode
- Write, then read back
- Loop line by line
- Watch a file get read
Text that outlives the program
Variables vanish when a program ends. A file keeps its text until you change it.
Opening a file safely
This line opens a log so you can add to it. Tap each part to see its job.
Write and read files
Pick an example, change it, then press Run. Say what you expect to see before you press. Each Run starts with no files, so every example writes its own.
Watch a file get read
Press Step to run one line at a time. Watch the names box change.
Quick guesses
Guess first, then read why. A wrong guess is where the learning happens. Nothing here is scored.
Common file misconceptions
Each card is something learners often believe. Tap it to see what Python really does.
Notes
Everything above, in words. Open it when you want the full explanation.
Syntax
The general shape of the statements in this lesson.
Worked examples
Read the problem, run the code, then read why it works.
Common pitfalls
Mistakes people make with this topic, and what to write instead.
In the real world
Where this shows up in software people use every day.
Key takeaways
Common questions
Guess the answer first, then open it.
Your notes
Sign in to keep private notes alongside this lesson.
Where to go next
The quiz and the Lab live on their own pages, so this lesson stays about learning.
Finished this lesson?
Create an ID or sign in to save your progress across devices.
Quiz
Check what you learned
12 questions, with an explanation after every answer. A finished attempt is marked on the server and earns XP.
Lab
Keep going in the Lab
7 tasks on this lesson, from writing code to tracing it by hand. Practice only, no XP.
Review
Spaced review
Questions you miss in a quiz come back on a spaced schedule, so what you learned here sticks.
This lesson at a glance
The 9 lines of code this lesson uses, each with a short note. Keep it open while you do the quiz and the Lab.
What else you can search for and explore
Curious to go further? Each one opens a web search in a new tab.
References
Look things up here whenever you need the exact details.
- open()Open a file so you can read from it or write to it.
- read()Read at most size characters or bytes from the file.
- write()Write a string or bytes to the file stream.
- close()Flush and close the open file handle.
- Reading and writing filesOfficial Python documentation
- The io moduleOfficial Python documentation