Python Programming · Foundations

Writing Files

Want it in plain words first? Jump to Eli explains — the same idea, no jargon.
On this page 9 sections
  1. In 30 seconds
  2. Why this matters
  3. The college version
  4. Eli explains
  5. Worked example
  6. Key takeaway
  7. Quick check
  8. Study tools
  9. Sources & references

In 30 seconds

Writing a text file means sending strings from a Python program to a named location on disk. Use with open(path, mode, encoding="utf-8") as file: so Python closes the file when the block ends. Mode "w" starts a new text file or replaces an existing file's contents; mode "a" adds new output at the end. write() writes one string, while writelines() writes strings from an iterable without inserting newlines for you.

Why this matters

Files let a program preserve output after the program stops: a report, a log, an exported list, or a configuration it generated. The key design decision is not merely how to call write, but what should happen to existing content. Choosing w when preservation was expected can erase a prior file; choosing a when a fresh report was expected can mix old and new results. A and an explicit text make ordinary output code clearer and more portable.

The college version

Opening a text file for an intentional kind of write

Python's built-in open() returns a connected to a path. For ordinary text output, a clear pattern is with open("report.txt", "w", encoding="utf-8") as file: followed by an indented block. The path says where the output goes; the mode says what kind of access is requested; and the encoding says how Python converts text strings to bytes for storage. This lesson uses UTF-8 explicitly because Python's documentation notes that an unspecified text encoding is platform-dependent and recommends UTF-8 unless another encoding is known to be needed. An encoding is not decoration: it is the agreed mapping between characters in a Python string and stored bytes.

The mode changes the consequences of the operation. "w" opens a file for writing and truncates it if it already exists. In plain language, a successful w write begins with an empty file; it is suitable for a report whose complete current version should replace an old version. "a" opens for appending, so new output is written at the end. It suits a simple log where a new event should follow earlier events. Neither mode is universally safer. The correct choice follows the program's promise to its user. Before using w, decide whether replacement is really intended; before using a, decide whether retaining prior entries is really intended. Exclusive creation (x) and file-existence handling are useful adjacent concerns, but they are outside this focused lesson.

The context manager owns the closing boundary

A file is a resource with a lifecycle. A program opens it, uses it, and should close it. The with statement creates a context-managed block: Python binds the opened file object after as file, runs the block, and closes the file when the block is left, including when normal flow leaves it because the block finishes. That makes the intended lifetime visible in the code. It also avoids relying on a later, easily forgotten file.close() call. The official tutorial presents this pattern as good practice because the file is properly closed after its suite finishes.

Closing matters because buffered output may need to be finalized and because a program should release resources it no longer needs. The practical rule is simple: keep the write operations inside the with block and do not try to use the file object as an open writer after the block. A context manager does not decide what content belongs in a file or protect a program from choosing w accidentally. It handles the resource boundary; the programmer still chooses the path, mode, encoding, and strings deliberately.

This lesson is about producing output, not inspecting it afterward. Reading a file is covered separately. In real work, a program may later verify output through a read or test, but that is a distinct workflow. Likewise, detailed exception strategies belong with exceptions. Here, the dependable starting pattern is an explicit text encoding plus a short with block whose purpose is to write the planned content.

Writing strings, lines, and delimiters

file.write(text) accepts one string and returns the number of characters written. It does not automatically add a line break. Thus file.write("First line") followed by file.write("Second line") produces adjacent text unless the programmer includes a separator such as "\n". A is data in the string, not an invisible side effect of write. This detail is important for line-oriented formats and logs: a visual line in source code is not automatically a line in the output file.

file.writelines(lines) writes each string from an iterable of strings. Despite its name, it also does not add line separators. A useful call is file.writelines(["April\n", "May\n"]), where each supplied string already carries its own newline. If the supplied strings are ["April", "May"], the stored result is AprilMay. Use write when one constructed string is clearest; use writelines when the program already has a sequence of complete string fragments or line strings. Neither method turns arbitrary values into text automatically, so format numbers or other data into strings before passing them.

A good output design makes separators visible. For a small report, collecting strings with explicit \n characters can be more readable than scattering many write calls. For a log, a single write call that includes one message and one terminating newline is often enough. The point is not to prefer one method by habit. State the output structure first, then choose the method whose input naturally matches that structure. This lesson deliberately does not cover parsing the resulting text, binary files, or error recovery; those need separate decisions and examples.

Eli, the EliExplains learning guide

Eli explains

The same idea, in plain words

Explain it like I’m 10

Think of a text file as a notebook your program can leave on a shelf. Opening it with w is like taking out the old pages and starting a replacement notebook. Opening it with a is like keeping the old pages and writing the next note after them. write() puts down the exact text you hand it; it does not press Enter by itself. To make a new line, include \n. A with block is the routine for borrowing the notebook: take it out, write during the marked time, and put it away when the marked time ends.

Picture it like this

A context-managed file write is like using a library desk: the desk checks out the item for one defined session and handles its return when the session ends.

Where the picture stops working

A file is not a physical notebook: modes can replace or append stored bytes, encodings determine how characters are represented, and closing a file can finalize buffered program output.

Worked example

This program creates or replaces a small text report, then appends one later line. It was executed with Python 3.

from pathlib import Path

path = Path("notes.txt")
with open(path, "w", encoding="utf-8") as file:
    count = file.write("First line\n")
    file.writelines(["Second line\n", "Third line\n"])

with open(path, "a", encoding="utf-8") as file:
    file.write("Fourth line\n")

print(count)

The output from print(count) is 11, because First line\n has 11 characters. The first block uses w, so it starts the file with the first three lines. writelines receives strings that already include \n; it supplies no separators of its own. The second block uses a, so its write follows the earlier contents. The resulting file has four separate lines, ending with Fourth line.

Key takeaway

For predictable text output, use a short with open(..., encoding="utf-8") block, choose w only for intended replacement and a only for intended addition, and put every required newline in the strings you write.

Quick check

3 questions here, of 5 in this lesson’s practice set. Answers stay hidden until you check.

Question 1 of 3foundational

What happens when an existing text file is opened with mode "w"?

Choose an answer, then check it.
Question 2 of 3intermediate

Which call writes two separate lines with writelines()?

Choose an answer, then check it.
Question 3 of 3intermediate

Why does this pattern use with open("log.txt", "a", encoding="utf-8") as file:?

Choose an answer, then check it.
Practice all 5

Keep learning

Ready to build on this? Continue to the next lesson.

Practice this lesson
Study tools & related lessonsYou’ll learn to · Common mistakes · Easily confused · Key vocabulary · Related

You’ll learn to

  • Distinguish text-file modes w and a by their effect on existing content.
  • Use with open(..., encoding="utf-8") to write a text file.
  • Explain the difference between write() and writelines().
  • Apply explicit newline characters when producing separate text lines.
  • Analyze which writing mode fits a fresh report versus an added log entry.

Common mistakes

  • Using mode w when earlier content was supposed to remain.

    Use a for intentional addition, or choose a different design after deciding the replacement policy.

  • Expecting write() to place each call on a new line.

    Include \n or another intended delimiter in the string.

  • Expecting writelines() to insert separators.

    Place newline characters in the supplied strings when separate lines are needed.

  • Leaving the encoding implicit for ordinary portable text output.

    Specify encoding="utf-8" unless the task requires and documents another encoding.

  • Keeping a writer open beyond the small block that needs it.

    Use with open(...) as file: and perform the related writes inside its block.

Easily confused

`w` mode vs. `a` mode

w writes from an empty file and truncates an existing one; a directs new writes to the end of existing content.

`write()` vs. `writelines()`

write() accepts one string; writelines() writes strings from an iterable, and neither inserts newline characters automatically.

Key vocabulary

file object
The Python object returned by open() that provides operations on an opened file.
text mode
A file mode in which Python reads or writes strings using a character encoding.
encoding
A mapping used to convert text characters to stored bytes and back.
truncate
To reduce a file to zero length; opening an existing file with mode w does this before writing.
append
To add new output after the existing contents of a file.
context manager
An object used with with to set up and clean up a resource around a block of code.
newline
A character sequence such as \n that separates lines in text output.

Sources & references

  1. Built-in Functions — Python 3 documentation — Python Software Foundation
  2. The Python Tutorial — 7. Input and Output (Reading and Writing Files) — Python Software Foundation
  3. Python Library Reference — io: Core tools for working with streams — Python Software Foundation

EliExplains lessons are original prose written from the open, credible references above. See Copyright & Licensing.

Researched 2026-08-19

Educational content only. It is not medical, legal or professional advice. Found an error? Tell us.