Learn Without Walls
← Previous Lesson Lesson 2 of 4 Next Lesson →

Lesson 11.2: Writing Files

What you will learn:

1. Write Mode ("w")

To write to a file, open it with mode "w" (write). This mode creates the file if it does not exist, or overwrites it if it does.

Warning: Write mode ("w") erases all existing content in the file! If the file already has data, that data will be lost. Use append mode ("a") if you want to keep existing content.

Writing to a File

# Create (or overwrite) a file
file = open("output.txt", "w")
file.write("Hello, World!\n")
file.write("This is my first file.\n")
file.write("Python is great!\n")
file.close()

The file output.txt now contains these three lines.

Note: The write() method does not automatically add a newline. You must include \n yourself if you want each piece of text on its own line.

2. Append Mode ("a")

Append mode adds new content to the end of an existing file without erasing what is already there. If the file does not exist, it creates a new one.

Appending to a File

# Add to the end of an existing file
file = open("output.txt", "a")
file.write("This line was added later.\n")
file.write("And so was this one.\n")
file.close()

Now output.txt has the original three lines plus these two new lines.

Practical Example: Logging

from datetime import datetime

def log_message(message):
    """Append a timestamped message to a log file."""
    timestamp = datetime.now().strftime("%Y-%m-%d %H:%M:%S")
    file = open("app.log", "a")
    file.write(f"[{timestamp}] {message}\n")
    file.close()

log_message("Program started")
log_message("User logged in")
log_message("Data processed successfully")

3. Using writelines()

The writelines() method writes a list of strings to a file. Like write(), it does not add newlines automatically.

Writing a List of Lines

lines = [
    "Alice: 95\n",
    "Bob: 87\n",
    "Charlie: 92\n",
    "Diana: 88\n"
]

file = open("scores.txt", "w")
file.writelines(lines)
file.close()

4. Creating New Files

Using write mode ("w") or append mode ("a") automatically creates a new file if it does not already exist. There is also an exclusive creation mode ("x"):

Exclusive Creation Mode

# "x" mode: creates a new file, but raises an error if file exists
try:
    file = open("new_file.txt", "x")
    file.write("This is a brand new file!\n")
    file.close()
    print("File created successfully!")
except FileExistsError:
    print("File already exists!")
Mode Description If File Exists If File Missing
"r"ReadOpens itError
"w"WriteOverwritesCreates new
"a"AppendAdds to endCreates new
"x"Exclusive createErrorCreates new

5. Writing with Variables and Loops

Writing Data from a Loop

students = {
    "Alice": 95,
    "Bob": 87,
    "Charlie": 92,
    "Diana": 88
}

file = open("report.txt", "w")
file.write("Student Report\n")
file.write("==============\n\n")

for name, score in students.items():
    status = "Pass" if score >= 90 else "Needs Improvement"
    file.write(f"{name}: {score} - {status}\n")

file.close()
print("Report saved!")
Report saved!

Check Your Understanding

What happens if you open an existing file with mode "w" and write to it?

The file's existing content is completely erased and replaced with the new content you write. This is why write mode can be dangerous if used carelessly. If you want to keep the existing content and add to it, use append mode ("a") instead.

Key Takeaways

← Previous Lesson Lesson 2 of 4 Next Lesson →