Historical Context & Motivation
Every program you have written so far probably loses its data the instant you close it. Variables live in RAM (random-access memory), which is fast but temporary. The moment the program ends or the power goes out, everything stored in RAM vanishes. Early computer scientists realized they needed a way to make data persist beyond a single session, and that led to the development of file systems and file I/O.
fopen() with mode flags such as "w" for write and "a" for append — concepts Python inherited directly.open() and later the with statement for safer file handling.The core question this lesson answers is straightforward: How does a Python program save text to a file, and what happens when you choose to write versus append? Understanding these file modes is essential because choosing the wrong one can accidentally erase hours of collected data.
Core Principles & Definitions
Before you write a single line of file-handling code, you need to understand four foundational ideas that govern how Python interacts with text files on your computer's storage.
File Object
open(), Python creates a file object — a connection between your program and a file on disk. Think of it as opening a pipeline that data can flow through.Write Mode ("w")
Append Mode ("a")
Closing the File
with statement ensures Python automatically closes the file, even if an error occurs.Visual Explanation — How File Modes Work
The diagram below illustrates the difference between write mode and append mode. On the left side, you can see how write mode replaces all existing content. On the right side, append mode preserves the original data and adds new text after it.
Notice the key difference highlighted in the diagram. On the left, the three original lines of data are completely removed when write mode opens the file — this happens immediately on opening, not when you call .write(). On the right, append mode jumps the cursor to the end of the existing content, so "New content" appears on a new line below the original three lines. This is why choosing the correct mode matters so much: you cannot undo a write-mode erase.
How File Writing Works in Python
The open() Function Syntax
"output.txt"). mode — a string that controls how the file is opened: "w" for write, "a" for append, or "r" for read (the default).The with Statement (Context Manager)
with block automatically calls f.close() when the block ends, ensuring data is flushed to disk and the file handle is released — even if an error occurs inside the block.Key Methods for Writing
Once you have a file object, Python gives you two primary methods for sending text into the file. The .write() method takes a single string and writes it to the file exactly as provided — it does not add a newline automatically, so you must include "\n" yourself if you want line breaks. The .writelines() method accepts a list of strings and writes them one after another, again without adding any newline characters between them. Most beginners stick with .write() because it makes your intentions clearer.
"\n" at the end of each string you write, all your text will run together on a single line in the output file. Always add "\n" when you want a new line.Detailed Breakdown of File Modes
Python supports several file modes, but for writing text files you will mainly use three. The table below compares them side by side so you can quickly decide which mode fits your situation.
| Mode | String | File Exists? | File Missing? | Cursor Position |
|---|---|---|---|---|
| Write | "w" | Erases all content | Creates a new file | Beginning |
| Append | "a" | Keeps all content | Creates a new file | End of file |
| Exclusive Create | "x" | Raises FileExistsError | Creates a new file | Beginning |
f.write() call, but the state of the file at that point depends on the mode you chose.The exclusive-create mode ("x") is a safety net you can use when you want to avoid accidentally overwriting an existing file. If the file already exists, Python raises a FileExistsError instead of silently deleting the old data. While you will not use "x" mode frequently as a beginner, knowing it exists helps you understand that Python gives you options to protect important data.
Worked Example — Building a Simple Log File
Suppose you are building a program that tracks daily weather temperatures. Each time the program runs, the user types in a city name and a temperature, and that entry should be saved so it is not lost. Let's walk through the code step by step.
input() to get the city and temperature, then format a single line of text that includes both values separated by a comma.
city = input("Enter city: ")
temp = input("Enter temperature (°F): ")
entry = city + "," + temp + "\n"entry is "Denver,72\n"with statement so the file closes automatically.
with open("weather_log.txt", "a") as f:with block, we call .write() to send the entry string to the file.
f.write(entry)"Denver,72\n" is appended to weather_log.txt.with block ends (and the file is safely closed), we print a confirmation message so the user knows the save was successful.
print("Entry saved!")city = input("Enter city: ")
temp = input("Enter temperature (°F): ")
entry = city + "," + temp + "\n"
with open("weather_log.txt", "a") as f:
f.write(entry)
print("Entry saved!")Write vs. Append — Strengths & Limitations
Neither write mode nor append mode is inherently "better." Each serves a distinct purpose, and picking the right one depends on whether you need a fresh start or want to accumulate data over time. The table below makes the trade-offs clear.
| Criteria | Write Mode ("w") | Append Mode ("a") |
|---|---|---|
| Best for | Generating a fresh report, overwriting config files, exporting final results | Log files, running totals, saving data from repeated runs |
| Risk | Accidentally deletes old data | File grows larger over time; no easy way to edit earlier entries |
| File creation | Creates new file if missing | Creates new file if missing |
| Cursor start | Beginning (byte 0) | End of existing data |
| Typical example | open("report.txt", "w") | open("log.txt", "a") |
Connection to Advanced File Handling
Writing plain text files is the foundation, but as your programs grow more complex, you will encounter structured data formats and more powerful I/O tools. The table below previews how the concepts you learned today connect to topics you will see in later courses.
| What You Know Now | What Comes Next |
|---|---|
Writing plain text with .write() | Writing structured data with the csv or json modules |
Modes "w" and "a" | Binary modes "wb" and "ab" for images, audio, etc. |
The with statement for safe closing | Writing custom context managers with __enter__ and __exit__ |
| Single-file output on your local machine | Database writes, cloud storage APIs, and network streams |
You will also learn about read-write mode ("r+" and "w+"), which lets your program both read from and write to the same file in one session. For now, the important takeaway is that mastering basic write and append modes gives you the mental model you need for every file-handling concept that follows.
Practice Problems
"w" and opening it with mode "a". Why would choosing the wrong mode be a problem?greeting.txt contain after the following code runs? Assume the file does not exist before execution.
with open("greeting.txt", "w") as f:
f.write("Hello\n")
f.write("World\n")scores.txt already contains the text "Alice,95\nBob,88\n". What will the file contain after each of the following code snippets runs independently?
Snippet A:
with open("scores.txt", "w") as f:
f.write("Carol,91\n")
Snippet B:
with open("scores.txt", "a") as f:
f.write("Carol,91\n")quotes.txt on a single line formatted as Name: Quote. The program should use a with statement. Explain why you chose append mode.highscores.txt. They ask you: should they use write mode or append mode? Justify your answer and describe what could go wrong with the other choice.Lesson Summary
Python's open() function creates a connection between your program and a file on disk. When you pass write mode ("w") as the second argument, the file is created if it does not exist or completely erased if it does. When you pass append mode ("a"), existing content is preserved and new text is added after it. Both modes use the .write() method to send strings to the file, and neither method adds newlines automatically — you must include "\n" yourself.
Always use a with statement when working with files so Python automatically closes the file and flushes buffered data to disk. Choose write mode when you need a fresh file every time (reports, exports) and append mode when you need to accumulate data across multiple runs (logs, collected entries). Mastering these two modes gives you the foundation for all future file I/O topics, from CSV and JSON to databases.