Concepts / Opening Files in Write Mode

Opening Files in Write Mode

Think of write() as a direct transfer: characters from the string argument move into the file, and the returned integer reports how many characters were written.

  • Programming

The Exact-Text Contract

When a file is open in write mode, the write() method puts the supplied data into the file exactly as provided. It does not add extra formatting on your behalf. The method also returns an integer representing the number of characters written.

Key point

Think of write() as a direct transfer: characters from the string argument move into the file, and the returned integer reports how many characters were written.

Tracing Consecutive Calls

What do you think happens?

Suppose the file starts empty. After write("red") followed by write("blue"), what text will the file contain?

  • red blue

  • redblue

  • red on one line and blue on the next

  • Only blue

Reveal answer
Answer:

redblue

The calls write their strings sequentially from the current file position. Neither string contains a newline, so the second string begins immediately after the first.

write("red")redwrite("blue")blueFileredbluenext callfinal content
What will the file contain after two write() calls with no newline characters?

Each consecutive write() call continues from the current file position. If the first call writes red and the next writes blue, the file contains redblue. A space appears only if a space is included in one of the strings; write() does not insert one automatically.

Return Values and Character Counts

The integer returned by write() is the character count written for that call. The count belongs to the string supplied in that call, not to the total contents of the file. If a call writes a five-character string, its return value reports five characters written. When a string includes a newline character, that newline is part of the supplied data and contributes to the characters written.

Worked example

Counting One Write

A call writes the string "Hello". What does its return value represent?

  1. 1
    Inspect the argument

    The string contains five characters: H, e, l, l, and o.

  2. 2
    Interpret the result

    The returned integer reports the number of characters written by this call.

Result

The return value is 5.

"Hello"5 charactersFile"Hello"5characters writtenwritten exactlycounted
How does the supplied string relate to the file data and the integer returned by write()?

Controlling Line Endings

Unlike print(), write() does not automatically add a newline. To place later text on a separate line, include the newline character \n in the string you write. Line formatting is therefore intentional: the location of \n determines where one line ends and the next begins.

"red"redblue"red\n"red"blue"same line"blue"next linenext writenext write
How does adding \n change the position of text written by the next call?
Worked example

Writing Two Lines

Predict the file contents after writing "first\n" and then "second".

  1. 1
    First call

    The first call writes first and then writes a newline character.

  2. 2
    Second call

    The second call begins after that newline, so second appears on the next line.

Result

The file contains first on the first line and second on the second line.

Mistakes with File Formatting

  • Common mistake

    Expecting write() to behave like print()

    What it looks like
    Calling write("first") and then write("second")
    Why it fails

    write() does not automatically add a newline, so the strings are written consecutively.

    Do this instead

    Include a newline explicitly, such as write("first\n"), when the next text should begin on another line.

  • Common mistake

    Adding a newline to the wrong string

    What it looks like

    Writing "first" and then writing "\nsecond"

    Why it fails

    The newline is processed at the start of the second call, rather than at the end of the first string.

    Do this instead

    Place the newline where the line should end, commonly at the end of the first string: "first\n".

  • Common mistake

    Treating the return value as the file's total size

    What it looks like

    Using the return value from a second write() call as the character count for the entire file

    Why it fails

    The return value reports the characters written by that call.

    Do this instead

    Interpret each return value in relation to its own string argument.

Prediction Practice

MEDIUM

A file starts empty. Predict its contents after these calls, then identify the return value of each call: write("A\n"), write("B"), and write("C\n"). Describe which strings appear on the same line and which newline characters end lines.

Hints
  • Trace the calls in order from the current file position.
  • Treat each \n as a character that moves the following text to the next line.
  • Count the characters supplied to each individual call.

To solve these problems, do not picture write() as a command that creates a formatted line automatically. Instead, read each string from left to right, place its characters at the current file position, and move to a new line only when the string contains \n.

Practical Takeaways

  1. 1
    write() places data into a file exactly as provided.
  2. 2
    The return value is the number of characters written by that call.
  3. 3
    Consecutive write() calls place their strings sequentially from the current file position.
  4. 4
    write() does not add newlines automatically.
  5. 5
    Include \n explicitly whenever the written text should continue on a new line.

At a glance

  • The write() method transfers the supplied text into a file without automatically changing it.
  • Its return value reports the number of characters written in that call.
  • Multiple calls write sequentially from the current file position.
  • Newline characters must be included explicitly to separate lines.
  • Predicting file contents requires tracing every character, including each \n.

More concepts starting with O