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.
fopen(), but far simpler to use.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.
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.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.
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.
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 |
"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.
"a"). If we mistakenly used "w", every time we ran the program it would erase all previous temperatures."a"with statement so the file is closed automatically. The code begins:
with open("temps.txt", "a") as f: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")with open("temps.txt", "r") as f:
print(f.read())temp = input("Enter today's high temp: ")
with open("temps.txt", "a") as f:
f.write(temp + "\n")
print("Temperature saved!")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 |
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 |
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
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?greeting.txt and writes exactly two lines: "Hello" on the first line and "World" on the second line. Use the with statement.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.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.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.