PY-101 ยท Files and errors
Reading and writing files
โฑ 8 min ๐ Real Python 3 ๐ฌ Animated โ Completed
โก The 30-second answer
open(name, mode) opens a file: "w" writes (replacing what was there), "a" appends to the end and "r" reads. Use .write() to save text and .read() or a for loop to read it back. Files hold text, so convert numbers with str() before writing.
- Write and append to a file
- Read a whole file or line by line
- Know the w, a and r modes
Try it
Watch it come alive, run it yourself, then prove it. Real Python, right on this page.
Watch Python run the example. Every variable is a jar; watch the values change and the output appear.
with open("tasks.txt", "w") as f:f.write("Buy milk\n")f.write("Call Ravi\n")with open("tasks.txt", "a") as f:f.write("Learn Python\n")with open("tasks.txt") as f:for number, line in enumerate(f, start=1):print(number, line.strip())
Change anything and press Run (or Ctrl+Enter). Then open Watch it and press Watch my code.
Input one line per input() call
Press Run to see the output. Python runs in your browser. Expected output
1 Buy milk
2 Call Ravi
3 Learn Python ๐ฏ Write each score in scores to scores.txt, one per line. Then read the file back and print the total of all the numbers (271).
Input one line per input() call
Press Run to see the output. Python runs in your browser. Need a hint?
Write str(s) + "\n" for each score; when reading, add int(line) for each line.
- The problemYour to-do app forgets everything when you close it. To remember tasks between runs, the program has to write them to a file and read them back next time.
- The Python idea
with open("file.txt", "w") as f:open(name, mode) opens a file: "w" writes (replacing what was there), "a" appends to the end and "r" reads. - In real lifeServers append a line to a log file for every request, and engineers read those logs when something breaks.
Start with a question
Your to-do app forgets everything when you close it. To remember tasks between runs, the program has to write them to a file and read them back next time.
Saving settings, logs, reports and exports all means writing files. Reading them is how scripts process data.
Explain it like I'm 10
A file is a notebook the program keeps in a drawer. "w" tears out the old pages and starts fresh, "a" adds to the last page, "r" just reads.
The technical explanation
with open("notes.txt", "w") as f: f.write("text\n") creates or replaces the file. \n ends a line.
with open("notes.txt") as f: text = f.read() reads it all. for line in f: reads one line at a time.
In this course the code runs in a private file system inside your browser, so nothing touches your computer.
Syntax
with open("file.txt", "w") as f:
f.write("text\n")
with open("file.txt") as f:
for line in f: ... Real-world scenario
Servers append a line to a log file for every request, and engineers read those logs when something breaks.
Test yourself
5 questions. Get 4 right and this lesson is marked complete.
Pass the quiz to complete this lesson.
๐ Every lesson counts toward your certificate Next: with and context managers โQuestions people ask
What is the difference between read(), readline() and readlines()?
read() returns the whole file as one string, readline() the next line, readlines() a list of all lines. Looping with for line in f is the most memory-friendly way.
Why should I specify encoding when opening files?
Different computers use different default encodings. open(name, encoding="utf-8") makes sure text like โน or รฉ reads the same everywhere.
Interview questions
How this topic comes up in Python interviews. Answer out loud first, then open the model answer.
beginner What is the difference between read(), readline() and readlines()?
read() returns the whole file as one string, readline() the next line, readlines() a list of all lines. Looping with for line in f is the most memory-friendly way.
beginner Why should I specify encoding when opening files?
Different computers use different default encodings. open(name, encoding="utf-8") makes sure text like โน or รฉ reads the same everywhere.
intermediate Which mode adds to the end of a file?
"a". "a" appends.
intermediate What does "w" do to an existing file?
Replaces its contents. Write mode starts the file again.
Quick revision
Remember
- Write and append to a file
- Read a whole file or line by line
- Know the w, a and r modes
- "w" wipes the file first. If you meant to add, use "a", or you will lose yesterday's data.
Syntax
with open("file.txt", "w") as f:
f.write("text\n")
with open("file.txt") as f:
for line in f: ... Official documentation
- Reading and writing files (docs.python.org)