Concepts / Writing Data to Files: The write() Method

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.

  • Programming
Interactive lab

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

  1. open(name, 'r') starts the pointer at 0; 'w' empties the file first; 'a' starts at the end.
  2. 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.
  3. 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.
  4. 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.
  5. 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.

Educational simulation

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?

  • Previous report

  • An empty file

  • Previous report followed by a blank line

  • The text w

Reveal answer
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.

output.txtPrevious reportopen()mode: woutput.txtemptyopen existing filetruncate
What happens to an existing file immediately after it is opened with open(filename, 'w')?

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().

python

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.

Existing fileold dataopen()mode: wEmpty filebefore write()New dataafter write()opentruncate immediatelywrite new text
Given an existing file and an opening operation, when does the old content disappear?

Replacing or Preserving

ModeExisting contentPosition for new dataTypical intention
wErased when the file is openedWriting begins in the cleared fileReplace the file contents
aPreservedNew data is added at the endAdd data without losing existing content

The central behavioral difference between write mode and append mode.

Existing datareportExisting datareportwclear firstapreserveNew datareplacementExisting data + newdataadditionopenwriteopenwrite at end
How does the file's content change when new data is written in w mode compared with a mode?
Best practice

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

Definition

The write() method puts data into a file exactly as provided and returns the number of characters written.

Code walkthrough
fout = open('message.txt', 'w')
count = fout.write('Ready')
  1. 1
    The first line opens the file in w mode. If message.txt existed, its old content is removed immediately; if it did not exist, Python creates it.
  2. 2
    The second line writes Ready to the file. The returned count is 5 because Ready contains five characters.
  • Open message.txt in 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.
Output
5
Ready5 characterswrite()exact textmessage.txtReady5characters writtenargumentstore textreturns
What data moves from the string argument into the file, and what does write() return?

Controlling 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.

python
Output
FirstSecond
Third

The 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().

write('First')no newlinewrite('Second\n')newline at endwrite('Third')no newlineFirstSecondthen Thirdnext positionafter newlinefinal content
How will consecutive write() calls appear when some strings contain \n and others do not?
File positionafter FirstSecondno \nFirstSecondsame lineSecond\nnewline includedNext textnew linewritecontinueswritemoves position
Why do strings written with write() stay on the same line unless a newline character is included?

Mistakes to Avoid

  • Common mistake

    Assuming w mode preserves old content

    What it looks like
    open('notes.txt', 'w')
    Why it fails

    Opening an existing file in w mode immediately truncates it.

    Do this instead

    Use 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 like
    fout.write('First')
    fout.write('Second')
    Why it fails

    write() places the strings exactly as supplied, so the result is FirstSecond.

    Do this instead

    Include \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 like
    count = fout.write('Ready')
    Why it fails

    write() returns the number of characters written, not the string itself.

    Do this instead

    Interpret count as a character count. For Ready, the count is 5.

  • Common mistake

    Thinking truncation waits until the first write() call

    What it looks like
    fout = open('output.txt', 'w')
    Why it fails

    Truncation happens when open() executes, before any write() call.

    Do this instead

    Predict the file state immediately after open() before tracing later statements.

Practice the Trace

MEDIUM

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 any write().
  • 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.
Worked example

Tracing the File

Assume log.txt initially contains Old. Determine the final content and the return value of each write() call.

  1. 1
    Open

    Opening log.txt in w mode erases Old immediately, so the file is empty before any writing.

  2. 2
    Write A

    The first call places A in the empty file and returns 1 because its argument contains one character.

  3. 3
    Write B newline

    The second call places B directly after A, then places the newline character. It returns 2 because B\n contains two characters.

  4. 4
    Write C

    The final call places C on the line after AB and returns 1.

Result

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

  1. 1
    Opening an existing file with w immediately erases its old content; if the file does not exist, Python creates it.
  2. 2
    Use w to replace a file and a to preserve existing content while adding new data at the end.
  3. 3
    write() stores the supplied data exactly as provided and returns the number of characters written.
  4. 4
    write() does not add newlines automatically, so include \n explicitly when line breaks are needed.
  5. 5
    Consecutive 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.

Related concepts

More concepts starting with W