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.
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
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 |
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')
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
Assuming w mode preserves old content
Opening an existing file in w mode immediately truncates it.
Fix:
Use w only when replacing the old contents is intentional. Use a when existing content must be preserved.Expecting write() to add a newline automatically
write() places the strings exactly as supplied, so the result is FirstSecond.
Fix:
Include \n in the string when the next text should begin on a new line.Treating the write() return value as the written text
write() returns the number of characters written, not the string itself.
Fix:
Interpret count as a character count. For Ready, the count is 5.Thinking truncation waits until the first write() call
Truncation happens when open() executes, before any write() call.
Fix:
Predict 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 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.
Tracing the File
Assume log.txt initially contains Old. Determine the final content and the return value of each write() call.
Open: Opening log.txt in w mode erases Old immediately, so the file is empty before any writing.
Write A: The first call places A in the empty file and returns 1 because its argument contains one character.
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.
Write 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
- Opening an existing file with w immediately erases its old content; if the file does not exist, Python creates it.
- Use w to replace a file and a to preserve existing content while adding new data at the end.
- write() stores the supplied data exactly as provided and returns the number of characters written.
- write() does not add newlines automatically, so include \n explicitly when line breaks are needed.
- Consecutive write() calls continue from the current file position, making newline placement determine the final layout.
Key Takeaways
- 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.