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.

Code braces with terminal and markup symbols representing Python programming.
Inside this lesson 10 sections 5 questions 5 figures

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

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.

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.

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!

SECTION 3

Visual Explanation

Write Mode ("w") vs Append Mode ("a")WRITE MODE ("w")notes.txt BEFORE:Line 1: Hello WorldLine 2: Old Datanotes.txt AFTER:Line 1: New Content(old data is gone!)APPEND MODE ("a")notes.txt BEFORE:Line 1: Hello WorldLine 2: Old Datanotes.txt AFTER:Line 1: Hello WorldLine 2: Old DataLine 3: New ContentPython Code Comparison# Write mode — overwriteswith open("notes.txt", "w") as f: f.write("New Content\n")# Append mode — adds to endwith open("notes.txt", "a") as f: f.write("New Content\n")Result: file contains ONLY "New Content"Result: file keeps old data + "New Content"
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.

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.

File Writing Lifecycle (with Statement)Step 1open(file, mode)Step 2f.write(data)Step 3 (automatic)f.close()Mode Details:"w" — Write Mode1. File is created if missing2. Existing content is ERASED3. Pointer starts at position 04. Only new data remains0"a" — Append Mode1. File is created if missing2. Existing content is KEPT3. Pointer starts at the END4. New data follows old dataEOF
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.

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.

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 file modes in Python

⚠

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.

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

    Step 2 — Open the File with a with Statement

    We 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. 3

    Step 3 — Write the New Temperature

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

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

When to use write vs append mode

✦

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.

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

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

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?
Show answer
The file contains exactly one line. When you open a file in write mode ("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

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.
Show answer
The correct code is: 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

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.
Show answer
First, write all scores: 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

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.
Show answer
The function should use append mode: 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

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.
Show answer
For 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.

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