Python open() function
Python open() function
The open() function in Python opens a file and returns a corresponding file object. If the file cannot be opened, an OSError is raised.
Syntax
open(file, mode='r', buffering=1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Parameter
file It represents the path and name of the file
mode It defines the string mode in which you want to open the file. The different modes are as follow:
Character |
Meaning |
'r' |
open for reading (default) |
'w' |
open for writing, truncating the file first |
‘x’ |
open for exclusive creation, failing if the file already exists |
‘a’ |
open for writing, appending to the end of the file if it exists |
‘b’ |
Binary mode |
‘t’ |
Text mode(default) |
‘+’ |
open a disk file for updating (reading and writing) |
buffereing This parameter is used for setting the buffering policy, and by default, its value is 1.
encoding It signifies the name of the encoding i.e to encode or decode the file.
errors This parameter represents a string specifying how to handle encoding/decoding errors.
newline This parameter determines how newlines mode works (available values: None, ' ', '\n', 'r', and '\r\n').
closefd This parameter must be True (default) else an exception will be raised.
opener This parameter represents a custom opener which returns an open file descriptor.
Return
This function returns a file object which can be used to read, write and modify a file.
Example 1
# Python program explaining # the open() function fun = open("demofile.txt", "r") print(fun.read())
Output
Hello World