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.
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
- "w" truncates existing files.
- write adds no newline.
- print(file=f) adds one.
Code examples
write returns a count; "w" truncates
13 second
writelines and print(file=)
['alpha', 'beta', 'gamma', 'delta']
More examples
Writing a formatted report
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:
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
Prefer
All names would end up on one line.
Writing a number
Avoid
Prefer
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
- 1Write a multiplication table for 7 to a file, one line per row.
- 2Save 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?