open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Opens a file and returns a file object representing it.
Parameters
file- a path-like object representing a path to the filesystem.mode(optional) — mode in which the file is opened. If not specified, the default is 'r' (open for reading in text mode).buffering(optional) — sets the buffering policy.encoding(optional) — encoding format.errors(optional) — string indicating how to handle encoding/decoding errors.newline(optional) — newline mode (available values:None,'','\n','\r', and'\r\n').closefd(optional) — must be True (default); otherwise, an exception is raised.opener(optional) — custom opener; must return an open file descriptor.
Available file modes:
| Mode | Description |
|---|---|
'r' | Open for reading. (default) |
'w' | Open for writing. Creates a new file if it does not exist or truncates the file if it exists. |
'x' | Open for exclusive creation. Fails if the file already exists. |
'a' | Open for appending to the end of the file without truncating it. Creates a new file if it does not exist. |
't' | Open in text mode. (default) |
'b' | Open in binary mode. |
'+' | Open for updating (reading and writing). |
Return Value
open()returns a file object that can be used to read, write, and modify the file.- If the file is not found, a
FileNotFoundErrorexception is raised.
Examples
# Open the file test.txt in the current directory
f = open("test.txt")
# Specify the full path
f = open("C:/Python/README.txt")