Python files: read, write and handle missing files

Reading and writing files lets a program keep data after it ends. The open function opens a file, a mode letter says what to do with it, and the with statement closes it when the block ends. With those three ideas, you can read a text file line by line, write a new file, and add to an existing file.
Files are easy to get wrong in small ways that look like larger problems. A file opened for reading in the wrong folder raises an error, even though the file exists somewhere else. A file opened for writing replaces its old contents, even though the program only meant to add one line. The examples in this guide use a small notes file, so each mistake and its fix can be seen in a few lines. If you have not run a program from the command line yet, start with your first Python program, which covers folders and commands.
Read a whole file and read it line by line
The read method returns the whole file as one string. That suits a short file that you want to print or search in one step. The example below opens notes.txt in read mode, which is the default mode, and prints its contents. The with statement opens the file, runs the block, and then closes the file, so you do not need a separate close call.
with open("notes.txt") as f:
text = f.read()
print(text)
Reading line by line suits a longer file, because the program handles one line at a time instead of holding the whole file in memory at once. Looping over the open file gives each line in turn, including its line break at the end. The strip method removes that line break and any extra spaces at the ends, which the strings guide explains in detail. Without strip, printed lines gain a blank line between them, because the line break from the file and the line break from print both appear.
with open("notes.txt") as f:
for line in f:
print(line.strip())
Write a new file and append to it
Write mode creates the file when it does not exist, and replaces its contents when it does exist. That replacement is the point to double-check before running a program that writes. The example below writes three lines to notes.txt. Each write call needs its own line break, written as \n, or the lines will run together into one long line.
with open("notes.txt", "w") as f:
f.write("Buy milk\n")
f.write("Call Sara\n")
f.write("Read chapter 3\n")
Append mode keeps the existing contents and adds new text at the end. It also creates the file when it does not exist, so it is safe for a log or a notes file that grows over time. The example below adds one line to the same file, without touching the lines already there.
with open("notes.txt", "a") as f:
f.write("Water the plants\n")
Writing a list of lines in one step uses writelines, which takes a list of strings and writes them in order. Like write, writelines does not add line breaks on its own, so each item in the list must already end with \n. A common pattern is to build the list first, check it with a print, and then write it, so a mistake in the data shows up before the file changes.
lines = ["Buy milk\n", "Call Sara\n"]
with open("notes.txt", "w") as f:
f.writelines(lines)
Handle a missing file without crashing
Opening a file for reading that does not exist raises FileNotFoundError, and the program stops unless that error is handled. The right response depends on the job. For a notes file, a missing file may simply mean no notes have been written yet, so starting with an empty list is sensible. For a settings file that the program needs, a missing file is a real problem, and a clear message is better than a silent empty result.
try:
with open("notes.txt") as f:
notes = [line.strip() for line in f]
except FileNotFoundError:
notes = []
print("No notes file found, starting with an empty list.")
print(notes)
The except block here follows the same rule as the error handling guide: catch the specific error, and give a plan for it. A bare except would also catch a spelling error in the file name variable, or a permission problem, and it would report both as a missing file. Catching FileNotFoundError alone keeps those cases separate, so a permission problem still shows up as a permission problem.
| Mode | File exists | File missing |
|---|---|---|
| r, read | Opens for reading | FileNotFoundError |
| w, write | Contents replaced | File created |
| a, append | New text added at end | File created |
| x, exclusive | FileExistsError | File created |
Common mistakes to watch for
Running a program from the wrong folder is the most common file mistake, and it produces FileNotFoundError for a file that exists in another folder. The command line folder and the program folder are not always the same, so check where the command runs before assuming the file name is wrong. Listing the files in the current folder, or printing the working folder from the program, settles the question in seconds.
Forgetting line breaks when writing is another frequent mistake. Write and writelines place text exactly as given, with no added breaks, so a list of words without \n becomes one long line. Add the break to each line, or join the lines with "\n" and add a final break, and then read the file back to check the result. Reading back what was written is a good habit for any file task, because it catches both missing breaks and wrong modes.
Opening a file without with, and then forgetting to close it, can leave text unwritten, because Python may hold the text in a buffer until the file closes. The with statement removes that risk by closing the file at the end of the block, even when an error occurs inside the block. If you see code that opens a file and never closes it, treat that as a bug to fix, not as a style choice.
Limits of plain text files
Plain text files suit notes, lists, and simple records, but they do not suit structured data with many fields. A line that packs several fields together with commas is hard to read back reliably when a field itself contains a comma. For structured records, a format designed for that job, such as JSON, is a better choice, and it is covered later in this series. A dictionary saved as plain text also loses its key and value structure, so save structured data in its own format instead of printing it to a file and trying to parse it back.
Text files also do not handle several programs writing at once. Two programs appending to the same file can mix their lines, and a program reading while another writes may see a partial line. For a beginner program run by one person at a time, that limit rarely matters. For a shared log or a program that runs on a schedule, a database or a proper logging setup is the right tool, and plain file writes should be treated as a learning step, not as a production design.
Worked example: save and reload a small list
A program that keeps a list between runs needs to save it to a file and read it back later. The example below writes each name on its own line, then reads the file back into a list, stripping the newline from each line. That round trip, save then reload, is the core pattern for simple persistent data, and it works for names, scores, and short notes.
names = ["Maya", "Ali", "Sara"]
with open("names.txt", "w", encoding="utf-8") as f:
for name in names:
f.write(name + "\n")
with open("names.txt", "r", encoding="utf-8") as f:
loaded = [line.strip() for line in f]
print(loaded)
Notice the write step adds a newline after each name, because write does not add one on its own. Without that newline, all names would run together on one line, and reading them back would give one long string instead of a list. The read step strips each line, so the reloaded names match the original names without trailing newlines.
The with statement deserves attention here. It opens the file, runs the block, and then closes the file, even when an error happens inside the block. Closing matters, because a file left open may not have its last writes flushed to disk, and another program may not be able to read it cleanly. Using with for every file operation removes that whole class of problem.
File modes in a table
Open modes decide what happens to an existing file and whether the program can read, write, or both. The table below lists the modes beginners use most, with the effect of each one on an existing file. Reading the table before choosing a mode prevents the most common file accident, which is opening an existing file for writing and emptying it by mistake.
| Mode | Meaning | Effect on an existing file |
|---|---|---|
| r | Read only | File must exist, content untouched |
| w | Write, create if missing | Content is emptied first |
| a | Append, create if missing | New content is added at the end |
| x | Create only | Fails when the file already exists |
| r+ | Read and write | Content untouched, position at the start |
Append mode suits a log, where each run should add lines without touching earlier lines. Exclusive creation mode suits an output file that must not overwrite an earlier result, because it fails loudly instead of silently replacing data. That loud failure is a strength, because it forces the program or the reader to choose a new name or to confirm the overwrite on purpose.
When a program must replace a file safely, a common pattern is to write to a temporary file first, then replace the original once the write succeeds. That pattern avoids a half-written file when the program crashes during writing, because the original stays intact until the new content is complete. For beginner programs, the simpler habit is to keep a backup copy of important data before running a program that writes in w mode.
Paths, folders, and relative locations
A relative path, such as "names.txt", means a file in the current working folder, which is the folder the command line was in when the program started. That folder is not always the folder holding the program file, which is a common source of confusion. A program run from a different folder will look for the file in that folder, and it will report the file as missing even though the file exists beside the program.
Building a path from the program file location removes that confusion. The pathlib module gives a clean way to do it, by starting from the file path of the running program and joining the data file name to its folder. That approach works no matter which folder the command line started in, because the path is anchored to the program rather than to the command line.
from pathlib import Path
base = Path(__file__).parent
path = base / "names.txt"
print(path)
Path objects also handle the difference between folder separators on different systems, so code written with pathlib does not need separate handling for each system. Joining parts with / works on the path object, and the resulting path prints in the form suited to the system it runs on. For beginner code, pathlib is worth learning early, because it prevents a whole set of path spelling problems.
Handle a missing file, and check the data after reading
A missing file should be handled with a clear message or a sensible default, rather than a crash that gives no guidance. The example pattern below catches FileNotFoundError and starts with an empty list, which suits a first run where no saved data exists yet. That default must be a deliberate choice, because starting empty also hides a misspelled file name, so the program should print a short note when it uses the default.
try:
with open("names.txt", "r", encoding="utf-8") as f:
loaded = [line.strip() for line in f]
except FileNotFoundError:
print("No saved file found. Starting with an empty list.")
loaded = []
Reading a file is only half the job. The data should also be checked, because a file can hold blank lines, extra spaces, or lines in the wrong shape. Stripping each line removes extra spaces, skipping blank lines avoids empty entries, and checking the shape of each line before using it prevents a later error far from the read step. That checking belongs close to the read, where the file shape is fresh in mind.
When a file holds structured data, such as numbers on each line, each line should be converted and checked in the same step. A line that does not convert should be reported with its line number, rather than stopping the whole read silently. That report makes the bad line easy to find in the file, and it keeps the rest of the data usable while the one bad line is fixed.
Frequently asked questions
What is the difference between write mode and append mode?
Write mode replaces the whole file, so old contents are lost when the file opens. Append mode keeps old contents and adds new text at the end, which suits logs and notes that grow over time.
Why does a file sometimes appear empty after writing?
The usual cause is reading the file before the writer closes it, or forgetting to close it at all. Using with closes the file at the end of the block, so the text is flushed and available for the next read.
Should a program create folders for its output files?
Yes, a program should check that the target folder exists before writing, or create it with a clear step. Opening a file in a missing folder raises an error, even when the file name itself is correct.
How do I read a file one line at a time without loading it all?
Loop directly over the open file object, which gives one line per pass without loading the whole file into memory. That pattern suits large files, because only the current line is held at a time.
Why is my file not found when it sits beside the program?
A relative path is resolved from the current working folder, which may differ from the folder holding the program file. Build the path from the program file location with pathlib to remove that confusion.
Should I close a file myself?
Using with closes the file when the block ends, even when an error happens inside it. That habit removes the risk of unwritten data and of a file left open for another program.


