Writing Data to Files: The write() Method
Write mode ('w') opens a file for writing and immediately truncates (erases) any existing content in the file.
Try it: Reading and Writing Text Files
How open() returns a file object with a position pointer, how read(), read(n), readline(), readlines() and for line in fh advance it (and return '' at the end), how 'w' and 'a' modes change the file, and why a closed file (after close() or a with block) can no longer be read.
How it works
- open(name, 'r') starts the pointer at 0; 'w' empties the file first; 'a' starts at the end.
- read() returns everything from the pointer to the end; read(n) at most n characters; readline() up to and including the next \n; each moves the pointer past what it returned.
- At the end of the file every read returns '' (an empty string), which is how loops know to stop; for line in fh reads line by line the same way.
- write() text waits in a buffer and reaches the file when it is closed (or the program ends); reading a 'w'/'a' file or writing an 'r' file raises io.UnsupportedOperation.
- close(), or leaving a with block, closes the file; any further read raises ValueError: I/O operation on closed file.
Default run (10 steps): Ready: notes.txt holds 4 lines (51 characters). Nothing is open yet. … Finished. notes.txt now holds "From: stephen\nSubject: meeting\nFrom: louis\nThanks!\n".
Simplified: The lab's own small Python interpreter runs a fixed, hand-written script (you choose the variant and the values, never the code); nothing is executed as real Python. Every script was run in CPython 3.12 with the same inputs and the lab reproduces its output and error messages. One virtual text file with \n line endings (as on Linux/macOS), positions counted in characters (ASCII only), and a write buffer that is only flushed by close() or the end of the program.
Loading the simulation…
The Opening Moment
Suppose notes.txt contains important information from yesterday. You run a Python program that opens notes.txt in write mode so it can save today's notes. Before the program writes even one character, yesterday's content is erased. The important event is not only what write() does. It is what open(filename, 'w') does immediately.
What do you think happens?
If output.txt already contains the text Previous report and Python evaluates open('output.txt', 'w'), what will the file contain immediately afterward?
Reveal answer
An empty file
Opening an existing file in w mode immediately truncates it. Truncation erases the existing content before any new data is written.
Write Mode State Changes
The mode parameter tells Python how the file will be used. The mode w opens a file for writing. If the named file does not exist, Python creates it. If the file already exists, Python immediately removes its old data. This happens when the file is opened, before the first call to write().
The name fout refers to a file object representing output.txt opened in write mode. At the moment open() finishes, the file has already been truncated. The variable fout gives the program the object it can use for writing; it does not delay the truncation until write() is called.
Replacing or Preserving
| Mode | Existing content | Position for new data | Typical intention |
|---|---|---|---|
| w | Erased when the file is opened | Writing begins in the cleared file | Replace the file contents |
| a | Preserved | New data is added at the end | Add data without losing existing content |
The central behavioral difference between write mode and append mode.
Choose w when the intended result is a fresh replacement, such as a newly generated report or configuration file. Choose a when new data must be added while preserving what is already there. The choice should be intentional because the modes have different effects on existing data.
What write() Puts There
The write() method puts data into a file exactly as provided and returns the number of characters written.
fout = open('message.txt', 'w')
count = fout.write('Ready')
- 1The first line opens the file in w mode. If
message.txtexisted, its old content is removed immediately; if it did not exist, Python creates it. - 2The second line writes Ready to the file. The returned count is 5 because Ready contains five characters.
- Open
message.txtin write mode. Existing content is truncated at this point. - Write the characters R, e, a, d, y exactly as provided and store the returned character count.
5Controlling Line Breaks
write() places the supplied data into the file exactly as provided. It does not automatically add a newline the way print() does. To end a line, include the newline character \n inside the string. Without it, a later write() call continues immediately after the earlier text at the current file position.
FirstSecond
ThirdThe first call writes First without ending the line. The second call therefore begins directly after it, producing FirstSecond, and its \n then moves the next write to a new line. The final call writes Third on that new line. Newline placement belongs to the strings you pass to write().
Mistakes to Avoid
Common mistake Assuming w mode preserves old content
What it looks likeopen('notes.txt', 'w')Why it failsOpening an existing file in w mode immediately truncates it.
Do this insteadUse w only when replacing the old contents is intentional. Use a when existing content must be preserved.
Common mistake Expecting write() to add a newline automatically
What it looks likefout.write('First') fout.write('Second')Why it failswrite()places the strings exactly as supplied, so the result is FirstSecond.Do this insteadInclude \n in the string when the next text should begin on a new line.
Common mistake Treating the write() return value as the written text
What it looks likecount = fout.write('Ready')Why it failswrite()returns the number of characters written, not the string itself.Do this insteadInterpret count as a character count. For Ready, the count is 5.
Common mistake Thinking truncation waits until the first write() call
What it looks likefout = open('output.txt', 'w')Why it failsTruncation happens when
open()executes, before anywrite()call.Do this insteadPredict the file state immediately after open() before tracing later statements.
Practice the Trace
Assume log.txt already contains Old. Predict the content of log.txt after each operation, in order:
fout = open('log.txt', 'w')
fout.write('A')
fout.write('B\n')
fout.write('C')Then predict the character count returned by each write() call.
Hints
- Apply truncation at the
open()operation, before anywrite(). - Place each string immediately after the preceding string.
- The newline character in the second string moves the final write to a new line.
- Count the characters in each individual argument, including any newline character.
Tracing the File
Assume log.txt initially contains Old. Determine the final content and the return value of each write() call.
- 1Open
Opening
log.txtin w mode erases Old immediately, so the file is empty before any writing. - 2Write A
The first call places A in the empty file and returns 1 because its argument contains one character.
- 3Write B newline
The second call places B directly after A, then places the newline character. It returns 2 because B\n contains two characters.
- 4Write C
The final call places C on the line after AB and returns 1.
The final file contains AB on the first line and C on the second line. The return values are 1, 2, and 1.
Key Takeaways
- 1Opening an existing file with w immediately erases its old content; if the file does not exist, Python creates it.
- 2Use w to replace a file and a to preserve existing content while adding new data at the end.
- 3
write()stores the supplied data exactly as provided and returns the number of characters written. - 4
write()does not add newlines automatically, so include \n explicitly when line breaks are needed. - 5Consecutive
write()calls continue from the current file position, making newline placement determine the final layout.
At a glance
- The w mode truncates an existing file as soon as it is opened.
- The a mode preserves existing content and adds new data at the end.
- The
write()method writes exactly the supplied string and returns its character count. - Newline characters must be included explicitly because
write()does not add them automatically.