Kahibaro
Discord Login Register

Writing and appending files

Writing Text to Files

When you write to a file, you create new content or replace existing content. In Python, you do this with the built-in open() function and a file object’s write() or writelines() methods.

The key idea:

Basic pattern for writing:

with open("notes.txt", "w", encoding="utf-8") as file:
    file.write("Hello, file!\n")
    file.write("This is a second line.\n")

Inside the with block, file is an object you can write to. When the block ends, the file is automatically closed.

Important points:

Overwriting vs creating

What happens when you use "w"?

Example:

# First run:
with open("todo.txt", "w", encoding="utf-8") as f:
    f.write("Buy milk\n")
# Second run (same code):
with open("todo.txt", "w", encoding="utf-8") as f:
    f.write("Buy bread\n")

After the second run, todo.txt will contain only:

Buy bread

The original "Buy milk" line is gone because "w" mode rewrote the file.

Writing multiple lines

You can collect lines in a list and then write them all at once with writelines().

lines = [
    "First line\n",
    "Second line\n",
    "Third line\n",
]
with open("lines.txt", "w", encoding="utf-8") as f:
    f.writelines(lines)

writelines() does not add newlines automatically; you must include "\n" in each string if you want separate lines.

Writing non-string values

write() and writelines() expect strings. If you have numbers or other types, convert them to strings first.

age = 25
temperature = 18.7
with open("data.txt", "w", encoding="utf-8") as f:
    f.write("Age: " + str(age) + "\n")
    f.write("Temperature: " + str(temperature) + "\n")

Or use f-strings:

with open("data.txt", "w", encoding="utf-8") as f:
    f.write(f"Age: {age}\n")
    f.write(f"Temperature: {temperature}\n")

Appending to Files

Appending means adding new content to the end of an existing file without erasing what was already there.

To append, use append mode: "a".

with open("log.txt", "a", encoding="utf-8") as f:
    f.write("Application started.\n")

If log.txt already has content, this line is added to the end. If it doesn’t exist yet, Python creates it and then writes to it.

Write vs append modes

Use this as a quick reference:

Example showing the difference:

# Step 1: Create file with one line (write mode)
with open("example.txt", "w", encoding="utf-8") as f:
    f.write("Line 1\n")
# Step 2: Add more lines (append mode)
with open("example.txt", "a", encoding="utf-8") as f:
    f.write("Line 2\n")
    f.write("Line 3\n")

Final content of example.txt:

Line 1
Line 2
Line 3

If you had used "w" in Step 2, Line 1 would have been erased.

Typical use cases for appending

Some common patterns where append mode is useful:

with open("events.log", "a", encoding="utf-8") as log:
    log.write("User logged in\n")
    log.write("User clicked 'Start'\n")
result = 42  # imagine we computed this earlier
with open("history.txt", "a", encoding="utf-8") as f:
    f.write(f"Result: {result}\n")

Each program run adds more lines, building a history.

Writing Lines Safely

When writing or appending, forgetting newline characters is a very common beginner mistake. Everything ends up on one long line.

Example of a problem:

with open("names.txt", "w", encoding="utf-8") as f:
    f.write("Alice")
    f.write("Bob")
    f.write("Charlie")

File content:

AliceBobCharlie

Better:

with open("names.txt", "w", encoding="utf-8") as f:
    f.write("Alice\n")
    f.write("Bob\n")
    f.write("Charlie\n")

Or use a loop:

names = ["Alice", "Bob", "Charlie"]
with open("names.txt", "w", encoding="utf-8") as f:
    for name in names:
        f.write(name + "\n")

Combining Read, Write, and Append

Sometimes you want to read a file and then write or append based on what you saw. Reading itself is covered elsewhere; here is how it might combine with write/append modes.

Example: copy a file and add a note at the end.

# Read original content
with open("original.txt", "r", encoding="utf-8") as source:
    content = source.read()
# Write to a new file (overwriting anything that was there)
with open("copy.txt", "w", encoding="utf-8") as target:
    target.write(content)
    target.write("\n--- End of copy ---\n")

Example: count lines and append a summary.

# Count lines
with open("data.txt", "r", encoding="utf-8") as f:
    lines = f.readlines()
line_count = len(lines)
# Append summary
with open("data.txt", "a", encoding="utf-8") as f:
    f.write(f"\nTotal lines: {line_count}\n")

Common Mistakes When Writing/Appending

Here are issues you are likely to see when starting out:

Forgetting to close files (without `with`)

If you do:

f = open("data.txt", "w", encoding="utf-8")
f.write("Hello")
# forgot f.close()

Some environments may still write correctly, but forgetting close() can cause problems. Using with avoids this risk.

Confusing modes `"w"` and `"a"`

Missing `encoding` (on some systems)

On many systems, omitting encoding works fine. On others, especially when working with non-English characters, it can cause problems. As a simple habit, you can always write text files with:

open("file.txt", "w", encoding="utf-8")
open("file.txt", "a", encoding="utf-8")

Writing non-strings directly

This will raise an error:

with open("numbers.txt", "w", encoding="utf-8") as f:
    f.write(123)  # TypeError

Fix by converting to string or using f-strings:

with open("numbers.txt", "w", encoding="utf-8") as f:
    f.write(str(123))
    # or
    f.write(f"{123}\n")

Small Practice Ideas

Here are simple exercises you can try using write and append modes:

  1. Diary file
    • Ask the user for a diary entry using input().
    • Append it to diary.txt with the current date on each line.
  2. Scoreboard
    • Write a program that:
      • Asks for a player name and score.
      • Appends "name: score" to scores.txt.
  3. Overwrite vs append demo
    • Use "w" mode to write numbers 1 to 5, each on its own line.
    • Then use "a" mode to add numbers 6 to 10.
    • Open the file manually and confirm the contents.

Views: 17

Comments

Please login to add a comment.

Don't have an account? Register now!