open()

Opens a file for reading or writing and returns a file object.

Returns
A file object.
On this page

Example

#
Python
with open("progress.txt", "w", encoding="utf-8") as file:
    file.write("HTML: done\n")
    file.write("CSS: in progress\n")

with open("progress.txt", encoding="utf-8") as file:
    for line in file:
        print(line.strip())
Resultsaved result, you can check it
HTML: done
CSS: in progress

Definition and usage

#

The open(path, mode) function opens a file. The mode "r" (the default) is for reading, "w" for writing with overwrite, "a" for appending at the end, and "x" creates a new file and raises an error if it already exists. The letter b in the mode means a binary file.

Always open a file inside a with block. It then gets closed automatically when the block ends, even if an error occurs.

For text files, pass encoding="utf-8". The default encoding depends on the system, so without it, accented characters can look different on different computers.

Syntax

#
Syntax
open(file, mode="r", encoding=None)

Parameters

#
  • file

    str or path

    The path to the file.
  • mode

    str, default "r"

    The mode: r, w, a, x, with an optional b or +.
  • encoding

    str, optional

    The text encoding, usually "utf-8".

Good practices

#
  • The "w" mode erases the contents already in the file. To append instead, use "a".
  • For working with paths, the pathlib module is more convenient: Path("file.txt").read_text(encoding="utf-8").

Related entries

#

Spotted a mistake or missing an example? Write to us.