Skip to content

Python open() function

  • by

Python open() function is used to open the file and returns the corresponding file object. It establishes the connection between a file and a file descriptor.

The open() function takes two parameters; filename, and mode.

open(file, mode) 
  • file: The path and name of the file
  • mode (optional) – mode while opening a file. If not provided, it defaults to 'r' (open for reading in text mode). Read more…

Note: If the file is not found, it raises the FileNotFoundError exception.

Python open() function example

A simple example code opens a file and prints the content.

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

Output:

Python open() function

Providing mode to open()

# opens the file in reading mode
f = open("path_to_file", mode='r')

# opens the file in writing mode 
f = open("path_to_file", mode = 'w')

# opens for writing to the end 
f = open("path_to_file", mode = 'a')

Do comment if you have any doubts or suggestions on this Python function topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Your email address will not be published. Required fields are marked *