Skip to content
Tutorials Center
My learning

Topics

Python Reference ยท Files, Paths and Text I/O

Python file.write() and writelines()

Reference for writing to a Python file object: write(), writelines(), flush(), buffering, missing newlines, the print(file=) shortcut and common mistakes.

file.write(s) writes one string (text mode) or bytes object (binary mode) to a file and returns how many characters or bytes were written. file.writelines(items) writes every item of an iterable in turn.

Neither adds a newline for you. If you want lines, put the \n in the data yourself, or use print(..., file=f), which does add one.

Python
with open("out.txt", "w", encoding="utf-8") as f:
    f.write("hello\n")

Try it

Python write(), writelines() and print(file=)

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Python Binary data, appending and common errors

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Syntax

Python
file.write(s)
file.writelines(lines)
Name Description
s A str for files opened in text mode, or a bytes-like object (bytes, bytearray, memoryview) in binary mode.
lines An iterable of strings (text mode) or bytes-like objects (binary mode).

Return value: write() returns the number of characters (text) or bytes (binary) written. writelines() returns None.

Raises: TypeError for the wrong data type (such as an int, or str in a binary file), io.UnsupportedOperation if the file was not opened for writing, ValueError if the file is closed, and OSError for problems such as a full disk.

Usage notes

  • No automatic newlines. writelines(["a", "b"]) writes ab, not two lines. Despite the name, it does not add line endings. Either include \n in each item or write "\n".join(items) + "\n".
  • Convert first. f.write(42) fails. Use f.write(str(42)), an f-string, or print(42, file=f).
  • Buffering. Data goes into a buffer first and reaches the disk when the buffer fills, on flush(), or when the file closes. Leaving a with block closes the file. If your program may crash and you need the data on disk, call f.flush() (and os.fsync(f.fileno()) for a hard guarantee).
  • "w" empties the file when it opens; use "a" to append, or "x" to refuse overwriting.
  • Newline translation. In text mode with the default newline=None, each \n you write becomes the platform line ending (\r\n on Windows).
  • Atomic replacement. To avoid half-written files, write to a temporary file and then os.replace() it over the target.
  • Many small writes are fast because of buffering, but building one string and writing it once is simpler for small data.
  • print(..., file=f) is convenient for formatted lines and separators (sep, end).