overview of open()
The open() function tries to open the specified file and if successful the corresponding file object is returned. If the file is not found a FileNotFoundError exception is raised.
use of open()
The open() function is most commonly used to overwrite a file or append content at the end of the file. Both variants are shown below.
# open in read mode
f1 = open('f1.txt')
# overwrite content in file
f2 = open('f2.txt', 'w')
# append content to file
f3 = open('f3.txt', 'a')
The open mode is specified in the second parameter and the most common values are: 'r' for reading mode, 'w' for writing mode and 'a' for appending mode. The default value is 'r'.
syntax of open()
The syntax of the open() function is:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
arguments of open()
The open() function accepts up to 8 arguments. The first argument is the filename and it is the only required argument, the following 7 arguments are optional.
argument |
required |
description |
file |
required |
the filename of the file to be opened |
mode |
optional |
the file mode to use, default value is 'r' |
buffering |
optional |
the buffering policy, default value is -1 |
encoding |
optional |
the encoding format, default value is None |
errors |
optional |
defines how to handle errors, default value is None |
newline |
optional |
defines how newlines are used, default value is None |
closefd |
optional |
must be True or an exception will be raised, default value is True |
opener |
optional |
defines a custom opener, default value is None |
return value of open()
If the specified file has been opened successfully, the open() function returns the file object. This file object can be used to read, write and modify the file later. Otherwise, if the file is not found, a FileNotFoundError exception is raised.