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.
with open("out.txt", "w", encoding="utf-8") as f: f.write("hello\n")
Try it
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.
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
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"])writesab, not two lines. Despite the name, it does not add line endings. Either include\nin each item or write"\n".join(items) + "\n". - Convert first.
f.write(42)fails. Usef.write(str(42)), an f-string, orprint(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 awithblock closes the file. If your program may crash and you need the data on disk, callf.flush()(andos.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\nyou write becomes the platform line ending (\r\non 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).