Python open() Function

Example

Open the file and print the content:

f = open("demofile.txt", "r")
print(f.read())

Run Instance

Definition and Usage

The open() function opens a file and returns it as a file object.

Please learn more about file handling in our file handling chapter.

Syntax

open(file, mode)

Parameter Value

Parameter Description
file The path or name of the file.
mode

String, define the mode in which you want to open the file:

  • "r" - Read - Default value. Open the file for reading, an error occurs if the file does not exist.
  • "a" - Append - Open the file for appending, create the file if it does not exist.
  • "w" - Write - Open the file for writing, create the file if it does not exist.
  • "x" - Create - Create the specified file and return an error if the file exists.

Additionally, you can specify whether the file should be processed in binary or text mode

  • "t" - Text - Default value. Text mode.
  • "b" - Binary - Binary mode (e.g., images).

Related Pages

Tutorial:How to Read File

Tutorial:How to Write/ Create File

Tutorial:How to Delete File