PYTHON • INPUT AND OUTPUT

Writing Files — Write text files and append vs overwrite modes

Learn how Python programs save data to text files using write and append modes.

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
IBM introduced the first commercial computer with a hard disk drive, enabling random-access file storage instead of sequential tape.
1969
Unix File System
Unix introduced the philosophy that "everything is a file," establishing the open-read-write-close pattern still used in Python today.
1991
Python 0.9 Released
Guido van Rossum released Python with built-in file I/O functions inspired by C's fopen(), but far simpler to use.
2008
Python 3 & the with Statement
Python 3 refined file handling and promoted the 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.

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.

1

Write Mode ("w")

Opens a file for writing. If the file already exists, its entire contents are erased. If the file does not exist, Python creates it.
2

Append Mode ("a")

Opens a file for writing, but new data is added to the end of any existing content. The file is created if it does not exist.
3

The with Statement

A context manager that automatically closes the file when the indented block finishes, even if an error occurs.
4

write() vs writelines()

The write() method writes a single string. The writelines() method writes a list of strings — but does not add newlines automatically.
✦ KEY TAKEAWAY
Think of write mode like erasing a whiteboard before writing a new message — everything old is gone. Append mode is like adding a new sticky note to a board that already has notes on it. The old notes stay, and your new note goes at the bottom. Choosing the wrong mode can accidentally delete data you wanted to keep!

Visual Explanation

The diagram above shows the critical difference between write mode and append mode. Notice how write mode erases the old lines before inserting new content, while append mode preserves the existing data and adds the new line at the bottom.

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.

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.

This flowchart illustrates the three-step lifecycle: open, write, and close. Note where the file pointer begins for each mode.

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.

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.

Common file modes in Python
ModeNameCreates File?Erases Content?Pointer Position
"r"Read (default)No — raises errorNoBeginning
"w"WriteYesYes — all data lostBeginning
"a"AppendYesNo — data preservedEnd of file
"x"Exclusive createYes — errors if existsN/ABeginning
"r+"Read & WriteNo — raises errorNoBeginning
⚠️ Common Pitfall
Opening a file with "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.

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 ModeSince 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 StatementWe use the with statement 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 TemperatureWe call f.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 FileAfter 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 ProgramHere 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.

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.

When to use write vs append mode
CriteriaWrite Mode ("w")Append Mode ("a")
Best forGenerating fresh reports, saving settings, exporting a complete data setLogging events, recording history, collecting data over time
Data safetyDangerous — erases old dataSafe — preserves old data
File size over timeStays the same (file is rebuilt each time)Grows larger with each run
Creates file if missing?YesYes
Typical exampleSaving a game config fileAdding entries to a log file
✦ KEY TAKEAWAY
Think of write mode like a dry-erase marker on a whiteboard — you wipe the board clean and start fresh every time. Append mode is like a pen in a notebook — you flip to the next blank page and keep writing. If your program collects data over time (like a log file or a journal), append mode is almost always what you want. If your program regenerates an entire file from scratch (like a report or a save file), write mode is appropriate.

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.

From basics to advanced file handling
What You Know NowWhat 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 safetyBuilding your own context managers with __enter__ and __exit__
Appending to a log fileUsing Python's logging module for professional-grade logging with timestamps and severity levels

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.

Practice Problems

PROBLEM 1 — CONCEPTUAL
A file called 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?
PROBLEM 2 — BASIC CALCULATION
Write a short Python program that creates a file called greeting.txt and writes exactly two lines: "Hello" on the first line and "World" on the second line. Use the with statement.
PROBLEM 3 — INTERMEDIATE
You have a list 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.
PROBLEM 4 — APPLIED
You are building a simple chat application. Each time a user sends a message, it should be saved to 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.
PROBLEM 5 — CRITICAL THINKING
Consider a program that runs once per day and writes a report to 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.

Lesson 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.

Varsity Tutors • Python • Writing Files — Write text files and append vs overwrite modes