Lesson 25 of 30 · Files, Errors and Modules
Reading and Writing Files
Save and load data with Python. Learn open(), the with statement, write, append and read modes, and how to read a file line by line.
- 7 min read
- Beginner
- Reviewed
- How to write text to a file
- How to read a file, all at once or line by line
- Why the with statement is the safe way to open files
- The difference between write mode and append mode
Why files?
Everything stored in a variable disappears when a program ends. To keep information, such as a list of scores, a set of notes or a dataset, a program must save it in a file.
Writing a file
with open("notes.txt", "w") as file:
file.write("Learn Python\n")
file.write("Build a project\n")
print("File saved.")Three things are happening.
open("notes.txt", "w")opens the file. The"w"is the mode, and it means write. If the file does not exist, Python creates it.as filegives the open file a name you can use.file.write(...)puts text in the file. Unlikeprint, it does not add a new line, so you add\nyourself.
\n is a special code that means "start a new line".
Why "with"?
A file must be closed when you finish, or your changes may not be saved. The with statement closes the file automatically when its indented block ends, even if an error happens inside it. Always open files this way.
Reading a whole file
Mode "r" means read. It is the default, so you can leave it out.
with open("notes.txt", "w") as file:
file.write("Learn Python\nBuild a project\n")
with open("notes.txt", "r") as file:
content = file.read()
print(content)read() returns the entire file as one string.
Reading line by line
For most tasks, going through a file one line at a time is more useful. A file can be used directly in a for loop.
with open("scores.txt", "w") as file:
file.write("Ada,92\nGrace,85\nAlan,78\n")
with open("scores.txt") as file:
for line in file:
line = line.strip()
name, score = line.split(",")
print(f"{name} scored {score}")Each line ends with an invisible \n. strip() removes it. split(",") then cuts the line into pieces at each comma.
Write mode replaces, append mode adds
Be careful: opening an existing file with "w" erases everything in it. To add to the end instead, use "a", for append.
with open("log.txt", "w") as file:
file.write("First entry\n")
with open("log.txt", "a") as file:
file.write("Second entry\n")
with open("log.txt") as file:
print(file.read())| Mode | Meaning | If the file exists | If it does not exist |
|---|---|---|---|
"r" | Read | Opens it | Error |
"w" | Write | Erases it and starts again | Creates it |
"a" | Append | Adds to the end | Creates it |
Saving a list to a file
Combine files with loops to save and load real data.
tasks = ["Write code", "Test code", "Deploy"]
with open("tasks.txt", "w") as file:
for task in tasks:
file.write(task + "\n")
loaded = []
with open("tasks.txt") as file:
for line in file:
loaded.append(line.strip())
print(loaded)When the file is missing
Reading a file that does not exist raises an error.
with open("missing.txt") as file:
print(file.read())You get FileNotFoundError. In the next lesson you will learn how to handle errors like this without the program stopping.
Common mistakes
The starter code creates a shopping list file. Read it back and print every item in capital letters.
with open("shopping.txt", "w") as file:
file.write("milk\nbread\neggs\n")
# Read shopping.txt line by line and print each item in CAPITALS.
# Output must be exactly:
# MILK
# BREAD
# EGGS
What happens when you open an existing file with open("data.txt", "w")?
Summary
open(name, mode)opens a file. Use it inside awithblock so the file is closed for you."w"writes and erases,"a"appends,"r"reads.write()does not add new lines. Add\nyourself.- Loop over a file to read it line by line, and
strip()each line.
Next: keeping your program running when something goes wrong.
Finished reading? Tick it off to track your progress.