112 of 151 menu

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

See also

  • method read,
    which reads the file
  • method readline,
    which reads the first line of the file
  • method readlines,
    which reads all lines of a file
  • method write,
    which writes a string to a file
  • method close,
    which closes the file
English
AfrikaansAzərbaycanБългарскиবাংলাБеларускаяČeštinaDanskDeutschΕλληνικάEspañolEestiSuomiFrançaisहिन्दीMagyarՀայերենIndonesiaItaliano日本語ქართულიҚазақ한국어КыргызчаLietuviųLatviešuМакедонскиMelayuမြန်မာNederlandsNorskPolskiPortuguêsRomânăРусскийසිංහලSlovenčinaSlovenščinaShqipСрпскиSrpskiSvenskaKiswahiliТоҷикӣไทยTürkmenTürkçeЎзбекOʻzbekTiếng Việt
We use cookies for website operation, analytics, and personalization. Data processing is carried out in accordance with the Privacy Policy.
accept all customize decline