KAHIBARO Bookshelves
Discord Login Register

10.3. 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:

  • Opening a file in write mode creates the file if it doesn’t exist,
    and erases everything in it if it does exist.

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:

  • "w" means write mode (start from scratch).
  • Each write() call writes exactly the characters you give it.
  • You must add "\n" if you want a newline.

Overwriting vs creating

What happens when you use "w"?

  • If notes.txt does not exist, it is created.
  • If notes.txt already exists, all its old content is deleted before writing.

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:

  • "w": write mode
    • Creates file if it doesn’t exist.
    • Erases all existing content.
    • Starts writing from the beginning.
  • "a": append mode
    • Creates file if it doesn’t exist.
    • Keeps existing content.
    • Adds new content at the end.

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:

  • Log files: recording events over time
with open("events.log", "a", encoding="utf-8") as log:
    log.write("User logged in\n")
    log.write("User clicked 'Start'\n")
  • Saving history (for example, a list of past calculations):
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"`

  • Using "w" when you meant "a" can silently erase important data.
  • A safe habit: when working with logs or histories, always double-check that you used "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: 0

Comments

Please login to add a comment.

Don't have an account? Register now!

Where to Move

Move chapter:

  • ☰ 1. Chapter 1: What Is Programming?
    • ☰ 1.1. What is a computer program?
      • ☰ 1.2. What is Python?
        • ☰ 1.3. Where is Python used?
          • ☰ 1.4. How programming helps solve problems
            • ☰ 1.5. Your first Python program
            • ☰ 2. Chapter 2: Setting Up Python
              • ☰ 2.1. Installing Python (Windows / macOS / Linux)
                • ☰ 2.2. Using Python in the terminal
                  • ☰ 2.3. Using an IDE (IDLE / VS Code)
                    • ☰ 2.4. Running Python scripts
                      • ☰ 2.5. Python interactive mode
                      • ☰ 3. Chapter 3: Variables and Data Types
                        • ☰ 3.1. What is a variable?
                          • ☰ 3.2. Creating variables
                            • ☰ 3.3. Numbers
                              • ☰ 3.4. Test
                                • ☰ 3.5. Boolean values
                                  • ☰ 3.6. Type checking
                                  • ☰ 4. Chapter 4: Basic Operations
                                    • ☰ 4.1. Arithmetic operations
                                      • ☰ 4.2. Working with numbers
                                        • ☰ 4.3. String operations
                                          • ☰ 4.4. Combining text and variables
                                            • ☰ 4.5. Comments in Python
                                            • ☰ 5. Chapter 5: User Input and Output
                                              • ☰ 5.1. Getting input from the user
                                                • ☰ 5.2. Converting input to numbers
                                                  • ☰ 5.3. Formatting output
                                                    • ☰ 5.4. Writing interactive programs
                                                    • ☰ 6. Chapter 6: Conditions
                                                      • ☰ 6.1. Comparison operators
                                                        • ☰ 6.2. Logical operators
                                                          • ☰ 6.3. if, elif, else
                                                            • ☰ 6.4. Nested conditions
                                                              • ☰ 6.5. Common beginner mistakes
                                                              • ☰ 7. Chapter 7: Loops
                                                                • ☰ 7.1. Why loops are useful
                                                                  • ☰ 7.2. for loops
                                                                    • ☰ 7.3. while loops
                                                                      • ☰ 7.4. Loop counters
                                                                        • ☰ 7.5. break and continue
                                                                          • ☰ 7.6. Loop exercises
                                                                          • ☰ 8. Chapter 8: Data Collections
                                                                            • ☰ 8.1. Lists
                                                                              • ☰ 8.2. Tuples
                                                                                • ☰ 8.3. Dictionaries
                                                                                  • ☰ 8.4. Sets (basics)
                                                                                    • ☰ 8.5. Choosing the right data structure
                                                                                    • ☰ 9. Chapter 9: Functions
                                                                                      • ☰ 9.1. Why functions matter
                                                                                        • ☰ 9.2. Defining functions
                                                                                          • ☰ 9.3. Parameters and arguments
                                                                                            • ☰ 9.4. Return values
                                                                                              • ☰ 9.5. Scope (local vs global)
                                                                                                • ☰ 9.6. Reusing code
                                                                                                • ☰ 10. Chapter 10: Working with Files
                                                                                                  • ☰ 10.1. What is a file?
                                                                                                    • ☰ 10.2. Reading text files
                                                                                                      • ☰ 10.3. Writing and appending files
                                                                                                        • ☰ 10.4. File paths
                                                                                                          • ☰ 10.5. Simple file-based programs
                                                                                                          • ☰ 11. Chapter 11: Errors and Debugging
                                                                                                            • ☰ 11.1. Types of errors
                                                                                                              • ☰ 11.2. Reading error messages
                                                                                                                • ☰ 11.3. Common beginner errors
                                                                                                                  • ☰ 11.4. try and except
                                                                                                                    • ☰ 11.5. Debugging strategies
                                                                                                                    • ☰ 12. Chapter 12: Using Python Libraries
                                                                                                                      • ☰ 12.1. What is a library?
                                                                                                                        • ☰ 12.2. Importing modules
                                                                                                                          • ☰ 12.3. Standard libraries
                                                                                                                            • ☰ 12.3.1. math
                                                                                                                              • ☰ 12.3.2. random
                                                                                                                                • ☰ 12.3.3. datetime
                                                                                                                                • ☰ 12.4. Installing external libraries with pip
                                                                                                                                • ☰ 13. Chapter 13: Object-Oriented Programming
                                                                                                                                  • ☰ 13.1. What is object-oriented programming?
                                                                                                                                    • ☰ 13.2. Classes and objects
                                                                                                                                      • ☰ 13.3. The `__init__` method
                                                                                                                                        • ☰ 13.4. Attributes and methods
                                                                                                                                          • ☰ 13.5. Encapsulation
                                                                                                                                            • ☰ 13.6. Inheritance (basics)
                                                                                                                                              • ☰ 13.7. Simple OOP examples
                                                                                                                                              • ☰ 14. Chapter 14: Automation with Python
                                                                                                                                                • ☰ 14.1. What is automation?
                                                                                                                                                  • ☰ 14.2. Automating simple tasks
                                                                                                                                                    • ☰ 14.3. Working with files and folders
                                                                                                                                                      • ☰ 14.4. Automating text processing
                                                                                                                                                        • ☰ 14.5. Scheduling scripts
                                                                                                                                                          • ☰ 14.6. Practical automation examples
                                                                                                                                                          • ☰ 15. Chapter 15: Web Development with Python
                                                                                                                                                            • ☰ 15.1. How the web works (basic overview)
                                                                                                                                                              • ☰ 15.2. Introduction to Flask
                                                                                                                                                                • ☰ 15.3. Creating a simple web server
                                                                                                                                                                  • ☰ 15.4. Routing and templates
                                                                                                                                                                    • ☰ 15.5. Handling user input (forms)
                                                                                                                                                                      • ☰ 15.6. Very basic APIs
                                                                                                                                                                      • ☰ 16. Chapter 16: Data Science with Python
                                                                                                                                                                        • ☰ 16.1. What is data science?
                                                                                                                                                                          • ☰ 16.2. Working with data
                                                                                                                                                                            • ☰ 16.3. Introduction to NumPy
                                                                                                                                                                              • ☰ 16.4. Introduction to pandas
                                                                                                                                                                                • ☰ 16.5. Data visualization with matplotlib
                                                                                                                                                                                  • ☰ 16.6. Simple data analysis examples
                                                                                                                                                                                  • ☰ 17. Chapter 17: Mini Projects
                                                                                                                                                                                    • ☰ 17.1. Number guessing game
                                                                                                                                                                                      • ☰ 17.2. Simple calculator
                                                                                                                                                                                        • ☰ 17.3. To-do list
                                                                                                                                                                                          • ☰ 17.4. Password generator
                                                                                                                                                                                            • ☰ 17.5. Quiz application
                                                                                                                                                                                              • ☰ 17.6. Small web or data project
                                                                                                                                                                                              • ☰ 18. Chapter 18: Next Steps
                                                                                                                                                                                                • ☰ 18.1. How to practice Python
                                                                                                                                                                                                  • ☰ 18.2. Writing clean and readable code
                                                                                                                                                                                                    • ☰ 18.3. Choosing a specialization
                                                                                                                                                                                                      • ☰ 18.3.1. Web development
                                                                                                                                                                                                        • ☰ 18.3.2. Data science
                                                                                                                                                                                                          • ☰ 18.3.3. Automation
                                                                                                                                                                                                            • ☰ 18.3.4. Software development
                                                                                                                                                                                                            • ☰ 18.4. Learning resources and communities
                                                                                                                                                                                                            • ☰ 19. Appendix
                                                                                                                                                                                                              • ☰ 19.1. Python syntax cheat sheet
                                                                                                                                                                                                                • ☰ 19.2. Common errors and solutions
                                                                                                                                                                                                                  • ☰ 19.3. Glossary of terms