Python open() Function
The Python open() function is used to open a file and returns it as a file object. It takes two parameters - filename and mode. Please see the syntax below:
Syntax
open(filename, mode)
Parameters
filename |
Required. specify filename with path which need to be opened. |
mode |
Optional. specify mode of opening the file. default is read mode for text file that is "rt". |
The different modes of opening a file are mentioned below:
Mode | Description |
---|---|
r | Default value. Opens a file for reading only. Raise an exception if the file does not exist. |
r+ | Opens a file for reading and writing. Raise an exception if the file does not exist. |
w | Opens a file for writing only. Creates the file if it does not exist. |
w+ | Opens a file for reading and writing. Creates the file if it does not exist. |
a | Opens a file for appending only. Creates the file if it does not exist. |
a+ | Opens a file for appending and reading. Creates the file if it does not exist. |
x | Creates the specified file. Raise an exception if the file already exists. |
x+ | Creates the specified file and Opens the file in reading and writing mode. Raise an exception if the file already exists. |
Apart from this, the file can be handled as binary or text mode
Mode | Description |
---|---|
t | Default value. Opens a file in the text mode. |
b | Opens a file in the binary mode. |
Example:
In the below example, open() function is used to open the file called python_test.txt in "rt" mode which means read text mode. The "rt" mode is also the default mode hence it does not require to specify.
MyFile = open("python_test.txt", "rt") # is equivalent to MyFile = open("python_test.txt")
In the below example, the file called python_test.txt is opened to read its content.
MyFile = open("python_test.txt", "r") print(MyFile.read())
The output of the above code will be:
Python is a programming language. Learning Python is fun.
❮ Python Built-in Functions