SECTION 1
Historical Context & Motivation
Long before modern computers, people needed ways to store information beyond the moment it was created. Early computing machines used punched cards and paper tape to persist data, but these methods were fragile and cumbersome. As computers evolved, the concept of a file system emerged — a structured way for programs to write data onto magnetic disks and retrieve it later. The ability to write to files meant that programs could save results, create logs, and communicate with other software, making computers far more useful.
1956 • IBM 305 RAMAC
1969 • Unix File System
1991 • Python 0.9 Released
fopen(), but far simpler to use.2008 • Python 3 & the with Statement
with statement as the standard, safe way to manage files.Today, almost every application you use — from note-taking apps to video games — writes data to files. The fundamental question this lesson addresses is: when your Python program saves data to a file, should it replace everything that was there before, or should it add new content to the end? Understanding this distinction is essential for building programs that handle data correctly.
SECTION 2
Core Principles & Definitions
Writing to a file in Python follows a simple three-step pattern: open the file, write your data, and close the file. The open() function is your gateway to the file system. It takes two main arguments: the file's name (a string) and the mode (also a string), which tells Python what you intend to do with the file. Choosing the right mode is one of the most important decisions you make when working with files.
Write Mode ("w")
Append Mode ("a")
The with Statement
write() vs writelines()
write() method writes a single string. The writelines() method writes a list of strings — but does not add newlines automatically.KEY TAKEAWAY
SECTION 3
Visual Explanation
As shown in the diagram, both modes use the same open() function and write() method. The only difference is the single-character mode string: "w" versus "a". That tiny change has a huge impact on what happens to your data. When you use "w", Python truncates (empties) the file the instant it opens it — before you even call write(). With "a", the file cursor is placed at the very end so your new data follows whatever was already there.
SECTION 4
How File Writing Works Under the Hood
When Python executes open("data.txt", "w"), several things happen behind the scenes. First, the operating system locates the file (or creates it if it does not exist). Then it sets the file pointer — an invisible cursor that tracks where the next write will go. In write mode, the pointer starts at position 0 (the very beginning) and the file's length is set to 0, effectively deleting all previous content. In append mode, the pointer is placed at the end of the existing content, so nothing is deleted.
The open() – write() – close() Lifecycle
Every file operation follows this lifecycle. The with statement simplifies it by automatically calling close() for you. Forgetting to close a file can lead to data loss because Python sometimes holds written data in a temporary memory buffer before flushing it to disk. Closing the file ensures all buffered data is saved.
The Newline Character
One important detail: write() does not automatically add a newline character at the end of your text. If you want each piece of data on its own line, you must include "\n" at the end of the string yourself. Without it, consecutive writes will smash text together on the same line, which is almost never what you want.
SECTION 5
A Closer Look at File Modes
Python supports several file modes beyond just "w" and "a". Understanding the full table of modes helps you pick the right one for each situation. The table below focuses on the modes most commonly used in text file writing.
| Mode | Name | Creates File? | Erases Content? | Pointer Position |
|---|---|---|---|---|
"r" | Read (default) | No — raises error | No | Beginning |
"w" | Write | Yes | Yes — all data lost | Beginning |
"a" | Append | Yes | No — data preserved | End of file |
"x" | Exclusive create | Yes — errors if exists | N/A | Beginning |
"r+" | Read & Write | No — raises error | No | Beginning |
Common file modes in Python
Common Pitfall
"w" mode erases all existing data immediately — even before you write anything. If you accidentally open an important file in write mode, its contents are gone. Always double-check your mode string, and use append mode when you want to keep existing data.write() vs writelines()
The write() method takes a single string argument and writes it to the file. If you have multiple lines to write, you can call write() multiple times or use writelines(), which takes a list of strings. A very common mistake with writelines() is assuming it adds newline characters between items — it does not. You must include "\n" at the end of each string in the list yourself.
SECTION 6
Worked Example
Let's walk through a realistic scenario. Imagine you are building a program that logs the daily high temperature. Each day, a new temperature should be added to a file called temps.txt without erasing previous entries.
Building a Temperature Logger
- 1
Step 1 — Choose the Right Mode
Since we want to keep old data and add new data at the end, we choose append mode ("a"). If we mistakenly used"w", every time we ran the program it would erase all previous temperatures.Mode selected:"a" - 2
Step 2 — Open the File with a with Statement
We use thewithstatement so the file is closed automatically. The code begins:with open("temps.txt", "a") as f:File opened in append mode, pointer at end of existing content. - 3
Step 3 — Write the New Temperature
We callf.write()with the temperature string. Remember to include"\n"so each entry is on its own line:f.write("2025-01-15: 72°F\n")The string "2025-01-15: 72°F" is appended on a new line at the end of the file. - 4
Step 4 — Verify by Reading the File
After closing, we can open the file in read mode to check our work:with open("temps.txt", "r") as f:print(f.read())Output shows all previous temperatures plus the new one at the end. - 5
Step 5 — Complete Program
Here is the full program that asks the user for today's temperature and logs it:temp = input("Enter today's high temp: ")with open("temps.txt", "a") as f:f.write(temp + "\n")print("Temperature saved!")Each time the program runs, the new temperature is added without losing previous data.
SECTION 7
Write vs Append — Strengths & Limitations
Neither write mode nor append mode is inherently "better" — each is the right tool for a specific job. The key is understanding when to use each one. The table below summarizes the strengths and trade-offs of each mode.
| Criteria | Write Mode ("w") | Append Mode ("a") |
|---|---|---|
| Best for | Generating fresh reports, saving settings, exporting a complete data set | Logging events, recording history, collecting data over time |
| Data safety | Dangerous — erases old data | Safe — preserves old data |
| File size over time | Stays the same (file is rebuilt each time) | Grows larger with each run |
| Creates file if missing? | Yes | Yes |
| Typical example | Saving a game config file | Adding entries to a log file |
When to use write vs append mode
KEY TAKEAWAY
SECTION 8
Connection to Advanced File Handling
The write and append modes you have learned form the foundation for more advanced file operations. As your Python skills grow, you will encounter structured data formats, binary files, and libraries that build on these basic concepts.
| What You Know Now | What Comes Next |
|---|---|
Writing plain text with write() | Writing structured data with the csv and json modules |
Text mode ("w", "a") | Binary mode ("wb", "ab") for images, audio, etc. |
Using with open() for safety | Building your own context managers with __enter__ and __exit__ |
| Appending to a log file | Using Python's logging module for professional-grade logging with timestamps and severity levels |
From basics to advanced file handling
Another concept you may encounter is file encoding. By default, Python 3 uses UTF-8 encoding, which supports characters from virtually every language. You can specify a different encoding with the encoding parameter of open(), for example: open("data.txt", "w", encoding="utf-8"). For now, the default is fine for most high school projects, but knowing this exists will help when you encounter international text or legacy files.
SECTION 9
Practice Problems
Question 1: CONCEPTUAL
log.txt already contains three lines of text. You open it with open("log.txt", "w") and then write one new line. How many lines does the file contain after you close it, and why?Show answer
"w"), Python immediately erases all existing content (called truncation) before any writing occurs. The three original lines are deleted the moment the file is opened in this mode. Then your single write() call puts one new line into the now-empty file. This is why choosing the correct mode is so important — write mode is destructive.Question 2: BASIC CALCULATION
greeting.txt and writes exactly two lines: "Hello" on the first line and "World" on the second line. Use the with statement.Show answer
with open("greeting.txt", "w") as f: followed by f.write("Hello\n") and f.write("World\n"). Since we are creating a brand-new file with known content, write mode ("w") is appropriate. We include "\n" at the end of each string to place each word on its own line. The with statement ensures the file is automatically closed.Question 3: INTERMEDIATE
scores = [95, 87, 73, 100, 88]. Write code that saves each score on its own line in a file called scores.txt. Then write additional code that adds the score 91 to the end of the file without erasing the existing scores.Show answer
scores = [95, 87, 73, 100, 88] then with open("scores.txt", "w") as f: followed by for s in scores: and f.write(str(s) + "\n"). We use write mode here because we are creating the initial file. To add score 91 later: with open("scores.txt", "a") as f: followed by f.write("91\n"). We switch to append mode so the five existing scores are preserved. Note that we convert integers to strings with str() because write() only accepts strings.Question 4: APPLIED
chat_log.txt with their username and message (e.g., "Alice: Hey there!"). The log should never lose previous messages. Write a function save_message(username, message) that does this. Explain your choice of file mode.Show answer
def save_message(username, message): followed by with open("chat_log.txt", "a") as f: and f.write(username + ": " + message + "\n"). Append mode ("a") is the correct choice because a chat log must grow over time. Using write mode would erase the entire conversation history every time someone sends a new message. Each call to the function opens the file, adds one line at the end, and closes it. The newline character ensures each message appears on its own line for readability.Question 5: CRITICAL THINKING
daily_report.txt. The report should contain only today's data — yesterday's report should be replaced. However, the program should also keep a running history in report_history.txt. Describe which mode you would use for each file and explain your reasoning. Then describe what would go wrong if you accidentally swapped the modes.Show answer
daily_report.txt, use write mode ("w") because this file should only contain today's report — yesterday's data should be replaced. For report_history.txt, use append mode ("a") because it should accumulate every day's report over time. If you accidentally swapped the modes, daily_report.txt would grow endlessly with all past reports (making it confusing to read), while report_history.txt would only ever contain the most recent day's data, destroying the historical record. This scenario demonstrates that both modes are valuable tools — the skill lies in matching each mode to the correct use case.SUMMARY
Lesson Summary
Summary
Python provides a straightforward way to save data by writing to text files using the built-in open() function. The second argument to open() determines the file mode. Write mode ("w") erases all existing content and starts fresh, making it ideal for generating complete files from scratch. Append mode ("a") preserves existing content and adds new data at the end, making it perfect for logs, journals, and data collection over time.
Always use the with statement to ensure files are properly closed. Remember that the write() method does not add newline characters automatically — include "\n" at the end of each string. The most common mistake is opening a file in write mode when you intended to append, which can permanently destroy important data. By mastering these two modes, you have the foundational skills to build programs that persist data beyond a single session.