01 / 20

Writing Files
in Python

Learn how to create, write, and append text to files using Python's built-in file handling: master the difference between overwrite and append modes.

Python

What Is File Writing?

Programs often need to save data permanently: a high-score list, a log of events, or a report. When your program ends, all variables vanish from memory. Writing to a file puts that data on disk so it survives after the program stops.

The open() Function

To write to a file, you call open() with two arguments: the filename and the mode. The mode tells Python what you intend to do with the file.

f = open("notes.txt", "w") f.write("Hello, file!") f.close()

The File Lifecycle

1. Open open("f.txt","w") 2. Write f.write("data") 3. Close f.close() Saved! Open → Write → Close: every file operation follows this pattern

Write Mode: "w"

Opening a file with "w" means overwrite. If the file already exists, its contents are erased completely before your new data is written. If it doesn't exist, Python creates it.

with open("scores.txt", "w") as f: f.write("Player1: 100\n") f.write("Player2: 85\n")

Append Mode: "a"

Opening a file with "a" means append. New data is added to the end of whatever already exists. Nothing is erased. If the file doesn't exist, Python creates it (just like "w").

with open("log.txt", "a") as f: f.write("New entry added\n")

"w" vs "a": The Key Difference

Write "w" BEFORE Line 1: Hello Line 2: World Line 3: Python ERASED! AFTER New data only Append "a" BEFORE Line 1: Hello Line 2: World Line 3: Python KEPT! AFTER Line 1: Hello Line 2: World Line 3: Python Line 4: New data

The with Statement

The with statement is the recommended way to work with files in Python. It automatically closes the file when the block ends, even if an error occurs.

Without with
f = open("f.txt","w")
f.write("data")
f.close() # easy to forget!
With with
with open("f.txt","w") as f:
  f.write("data")
# auto-closed!

How to Write a File

1
Choose the mode: "w" to start fresh, or "a" to add to existing content.
2
Open the file using with open(filename, mode) as f:
3
Write your data using f.write(string). Remember to add \n for new lines.
4
Exit the with block: the file closes automatically. Your data is safely on disk.

Example 1: Creating a File

# Create a new file and write three lines with open("greeting.txt", "w") as f: f.write("Hello!\n") f.write("Welcome to Python.\n") f.write("Enjoy coding!\n")

Example 2: Appending to a Log

# Append a new entry every time the program runs from datetime import datetime now = datetime.now().strftime("%Y-%m-%d %H:%M") with open("log.txt", "a") as f: f.write(f"Ran at {now}\n")

Example 3: Writing with a Loop

students = ["Alice", "Bob", "Charlie"] scores = [95, 87, 92] with open("report.txt", "w") as f: for name, score in zip(students, scores): f.write(f"{name}: {score}\n")

Bonus: writelines()

If you have a list of strings ready to go, you can write them all at once with writelines() instead of looping over write().

lines = ["Line 1\n", "Line 2\n", "Line 3\n"] with open("output.txt", "w") as f: f.writelines(lines)

Common Mistakes

✕ Forgetting \n
Multiple write() calls without \n produce one long line instead of separate lines.
✕ Using "w" When You Mean "a"
Opening with "w" erases everything. If you need to keep old data, use "a" to append.
✕ Writing Non-Strings
write() only accepts strings. Passing an integer like write(42) raises a TypeError. Convert with str().

Mode Comparison Table

"w" (Write) "a" (Append) "r" (Read)
Creates file if missing? Yes Yes No (error)
Erases existing content? Yes No N/A
Writes to? Start of file End of file Cannot write
Best for? Fresh output Logs, history Reading input

Question 1 of 5

What happens when you open an existing file with mode "w"?

Question 2 of 5

Which mode should you use to add new lines to a log file without losing old entries?

Question 3 of 5

What is the main advantage of using the with statement when writing files?

Question 4 of 5

What does the following code produce in output.txt?

Code:

with open("output.txt", "w") as f:
    f.write("Hello")
    f.write("World")

Question 5 of 5

What happens if you call f.write(42) without converting to a string?