SECTION 1
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.
1951 • UNIVAC & Magnetic Tape
1965 • Multics File System
1972 • C Language & fopen()
fopen() with mode flags such as "w" for write and "a" for append — concepts Python inherited directly.1991 • Python's open() Function
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.
SECTION 2
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.KEY TAKEAWAY
SECTION 3
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.
SECTION 4
How File Writing Works in Python
The open() Function Syntax
BASIC SYNTAX
filename — a string with the file's name (e.g., "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)
RECOMMENDED PATTERN
The 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.
Common Pitfall
"\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.SECTION 5
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 |
Common file modes for writing text in Python
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.
SECTION 6
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.
Writing a Temperature Log to a File
- 1
Step 1 — Collect input from the user
We useinput()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"If the user types "Denver" and "72",entryis"Denver,72\n" - 2
Step 2 — Open the file in append mode
Because we want to keep previous entries every time the program runs, we choose append mode. We also use awithstatement so the file closes automatically.with open("weather_log.txt", "a") as f:Python either opens the existing file or creates a new one, with the cursor placed at the end. - 3
Step 3 — Write the entry to the file
Inside thewithblock, we call.write()to send the entry string to the file.f.write(entry)The line"Denver,72\n"is appended toweather_log.txt. - 4
Step 4 — Confirm to the user
After thewithblock ends (and the file is safely closed), we print a confirmation message so the user knows the save was successful.print("Entry saved!")Running this program three times with different inputs creates a file with three lines — no data is lost between runs. - 5
Step 5 — The complete program
Here is all the code together: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!")Each run adds one line to the file. Switching "a" to "w" would erase previous entries every time.
SECTION 7
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") |
Side-by-side comparison of write and append modes
KEY TAKEAWAY
SECTION 8
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 |
How today's skills scale into more advanced topics
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.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
"w" and opening it with mode "a". Why would choosing the wrong mode be a problem?Show answer
Question 2: BASIC CALCULATION
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")Show answer
greeting.txt will contain two lines: "Hello" on the first line and "World" on the second line. Since the file did not exist, write mode created it. The first .write() call writes "Hello" followed by a newline character, and the second call writes "World" followed by another newline. Each "\n" moves the cursor to the next line.Question 3: INTERMEDIATE
scores.txt already contains the text "Alice,95
Bob,88
". 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")Show answer
Question 4: APPLIED
quotes.txt on a single line formatted as Name: Quote. The program should use a with statement. Explain why you chose append mode.Show answer
name = input("Your name: ")
quote = input("Favorite quote: ")
with open("quotes.txt", "a") as f:
f.write(name + ": " + quote + "\n")
Append mode is the correct choice because the goal is to collect quotes from multiple users over multiple runs. If we used write mode, each new user's entry would erase all previously saved quotes. The with statement guarantees the file is closed properly even if the string concatenation somehow caused an error.Question 5: CRITICAL THINKING
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.Show answer
SUMMARY
Lesson Summary
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.