The open function
The open function opens a file and returns a file object.
The first parameter of the function specifies the path to the file we want to open.
In the second optional parameter, we set the flag - this is a string or number that specifies the file access mode (for example, reading). By default, the flag is 'r'.
The third optional parameter allows you to set the buffering mode (default is -1).
The fourth optional parameter is the encoding type (default is None).
In the fifth optional parameter, we specify how encoding errors should be handled (by default None).
The sixth optional parameter is the line feed mode, which can take the values None, '\n', '\r', '\r\n' (default is None).
The seventh optional parameter allows you to specify a file descriptor close flag (default True).
The eighth optional parameter is a custom object that returns an open file descriptor (default None).
Syntax
open(file path, [flags bunting], [buffering], [encoding type], [error mistake fault flaw fallacy miscarriage failing lapse slip trip misstep inaccuracy gaffe faux pas break stumble lapsus misdeed bungle misdoing muff clinker floater X slip-up chance-medley], [line translation], [closing flag], [custom object])
Example
Let's open the file file.txt and then use the read method to read its contents:
res = open('file1.txt', 'r')
print(res)
print(res.read())
The result of the executed code:
<_io.TextIOWrapper name='file1.txt' mode='r' encoding='cp1251'>
text