Skip to content

Module 13 · File Handling — topic 4 of 15

Writing

Writing text files with mode "w": write() and its return value, writelines(), print(..., file=f), adding line endings yourself, and producing formatted reports.

Beginner 8 min read·Lesson 197 of 306 in Python Programming

Learning objectives

  • Write text with write, writelines and print
  • Add line endings correctly
  • Produce formatted text reports

Definition

Writing stores data in a file opened with a writing mode. Mode "w" creates the file if needed and truncates it if it exists; f.write(text) writes a string and returns the number of characters written.

Introduction

Saving results — a report, an export, a list of high scores — means writing to a file. Python offers a few convenient ways to do it.

Why it matters

Writing is where data loss happens: one wrong mode erases a file. Knowing exactly what "w" does keeps your data safe.

Detailed explanation

open(path, "w", encoding="utf-8") creates the file, or empties it if it already exists — the old content is lost immediately.

f.write(s) writes the string s as-is and returns the number of characters written. It does not add a newline; include "\n" yourself.

f.writelines(iterable) writes each string in turn, again without adding newlines.

print(value, file=f) writes like print does on screen: it converts values to strings, separates them with spaces and adds a newline.

write() only accepts strings in text mode; convert numbers with str() or an f-string.

Data is buffered and reaches the disk when the file is flushed or closed — another reason to use with.

To avoid overwriting by accident, use mode "x" (fails if the file exists) or check first.

Syntax

Python
with open("out.txt", "w", encoding="utf-8") as f:
f.write("line one\n")
f.writelines(["two\n", "three\n"])
print("four", file=f)
  • "w" truncates existing files.
  • write adds no newline.
  • print(file=f) adds one.

Code examples

write returns a count; "w" truncates

Python
with open("out.txt", "w", encoding="utf-8") as f:
n = f.write("first version")
print(n)
with open("out.txt", "w", encoding="utf-8") as f:
f.write("second")
with open("out.txt", encoding="utf-8") as f:
print(f.read())
Output
13
second

writelines and print(file=)

Python
lines = ["alpha", "beta", "gamma"]
with open("list.txt", "w", encoding="utf-8") as f:
f.writelines(line + "\n" for line in lines)
print("delta", file=f)
with open("list.txt", encoding="utf-8") as f:
print(f.read().split())
Output
['alpha', 'beta', 'gamma', 'delta']

More examples

Writing a formatted report

Python
students = [("Asha", 91), ("Ravi", 78), ("Meera", 85)]
with open("report.txt", "w", encoding="utf-8") as f:
f.write(f"{'Name':<8}{'Marks':>6}\n")
f.write("-" * 14 + "\n")
for name, marks in students:
f.write(f"{name:<8}{marks:>6}\n")
avg = sum(m for _, m in students) / len(students)
f.write(f"{'Average':<8}{avg:>6.1f}\n")
with open("report.txt", encoding="utf-8") as f:
print(f.read(), end="")
Output
Name     Marks
--------------
Asha        91
Ravi        78
Meera       85
Average   84.7

Step-by-step explanation

  • Format specifiers align columns: <8 pads names on the right, >6 right-aligns marks.
  • Every line ends with "\n" added explicitly.
  • print(..., end="") avoids an extra blank line because the file already ends with a newline.

Expected output

Running “Writing a formatted report” prints exactly:

TextOutput
Name Marks
--------------
Asha 91
Ravi 78
Meera 85
Average 84.7

Practical applications

  • Exporting reports and receipts.
  • Generating configuration or source files.

Best practices

  • Remember "w" erases existing content.
  • Add "\n" explicitly or use print(file=f).
  • Use f-strings to format output.

Common mistakes

Forgetting newlines

Avoid

for name in names:
f.write(name)

Prefer

for name in names:
f.write(name + "\n")

All names would end up on one line.

Writing a number

Avoid

f.write(42)

Prefer

f.write(str(42))

write() requires a string in text mode (TypeError otherwise).

Important notes

  • For safe saving, write to a temporary file and then replace the original with os.replace, so a crash never leaves a half-written file.

Key takeaways

  • "w" creates or truncates.
  • write() writes strings without adding newlines.
  • print(file=f) is a convenient alternative.

Try it yourself

  1. 1
    Write a multiplication table for 7 to a file, one line per row.
  2. 2
    Save a shopping list with quantities and prices as an aligned text receipt.

Finished reading? Mark it complete to update your dashboard.

Suggested practice

8 questions cover the “File Handling” module. Answers and explanations are revealed after you submit.

  • ModerateWhat is printed?
  • ModerateWhat is printed?
  • ModerateWhich mode creates a new file but fails if the file already exists?
Practise this module