COMPUTER PROGRAMMING 1 (PYTHON) • FILES & DATA I/O

Writing Text Files — I can write output to a text file and explain file modes (write/append) at my level.

Learn how Python programs save data permanently by writing and appending text to files on disk.

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
The UNIVAC I computer used magnetic tape to store census data, marking one of the first times programs could write output that survived after the machine powered down.
1965
Multics File System
The Multics operating system introduced a hierarchical file system with directories and named files, giving programs a structured way to create and locate stored data.
1972
C Language & fopen()
The C programming language standardized file operations using functions like fopen() with mode flags such as "w" for write and "a" for append — concepts Python inherited directly.
1991
Python's open() Function
Guido van Rossum released Python, which wrapped file I/O in a clean, readable syntax using 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.

1

File Object

When you call 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.
2

Write Mode ("w")

Write mode creates a brand-new file or erases everything in an existing file before writing. It starts you with a blank page every time.
3

Append Mode ("a")

Append mode opens a file and places the cursor at the very end, so new data is added after existing content. Nothing is deleted.
4

Closing the File

Data may sit in a memory buffer until the file is closed. Using a with statement ensures Python automatically closes the file, even if an error occurs.
✦ KEY TAKEAWAY
Imagine a whiteboard in a classroom. Write mode ("w") is like erasing the entire board before you start writing fresh notes. Append mode ("a") is like picking up the marker and continuing below whatever is already on the board. Choosing the wrong mode is like accidentally erasing someone else's notes — so always double-check before you open a file.

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.

Left: Write mode ("w") erases existing content before writing. Right: Append mode ("a") keeps existing content and adds new text at the end. Both modes will create the file if it does not already exist.

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

BASIC SYNTAX
file_object = open(filename, mode)
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
with open(filename, mode) as f: f.write(text)
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
If you forget the "\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.

Common file modes for writing text in Python
ModeStringFile Exists?File Missing?Cursor Position
Write"w"Erases all contentCreates a new fileBeginning
Append"a"Keeps all contentCreates a new fileEnd of file
Exclusive Create"x"Raises FileExistsErrorCreates a new fileBeginning
Flowchart showing the decision tree when Python opens a file for writing. All paths converge at the 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.

Writing a Temperature Log to a File
1
Step 1 — Collect input from the userWe use 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"
If the user types "Denver" and "72", entry is "Denver,72\n"
2
Step 2 — Open the file in append modeBecause we want to keep previous entries every time the program runs, we choose append mode. We also use a with statement 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 fileInside the with block, we call .write() to send the entry string to the file. f.write(entry)
The line "Denver,72\n" is appended to weather_log.txt.
4
Step 4 — Confirm to the userAfter the 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!")
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 programHere 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.

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.

Side-by-side comparison of write and append modes
CriteriaWrite Mode ("w")Append Mode ("a")
Best forGenerating a fresh report, overwriting config files, exporting final resultsLog files, running totals, saving data from repeated runs
RiskAccidentally deletes old dataFile grows larger over time; no easy way to edit earlier entries
File creationCreates new file if missingCreates new file if missing
Cursor startBeginning (byte 0)End of existing data
Typical exampleopen("report.txt", "w")open("log.txt", "a")
✦ KEY TAKEAWAY
Think of your file like a notebook. Write mode rips out all the pages and gives you a fresh notebook every time. Append mode opens the notebook to the last page with writing and lets you continue from there. For any situation where you need to keep a running history — like game high scores or a chat log — append is your friend.

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.

How today's skills scale into more advanced topics
What You Know NowWhat 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 closingWriting custom context managers with __enter__ and __exit__
Single-file output on your local machineDatabase 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

PROBLEM 1 — CONCEPTUAL
Explain in your own words the difference between opening a file with mode "w" and opening it with mode "a". Why would choosing the wrong mode be a problem?
PROBLEM 2 — BASIC CALCULATION
What will the file 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")
PROBLEM 3 — INTERMEDIATE
A file called 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")
PROBLEM 4 — APPLIED
Write a short Python program that asks the user for their name and a favorite quote, then appends both to a file called quotes.txt on a single line formatted as Name: Quote. The program should use a with statement. Explain why you chose append mode.
PROBLEM 5 — CRITICAL THINKING
A classmate writes a program that is supposed to save the top 10 high scores for a game. Every time a new high score is earned, the program should rewrite the entire top-10 list to 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.

Varsity Tutors • Computer Programming 1 (Python) • Writing Text Files — I can write output to a text file and explain file modes (write/append) at my level.