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.
- 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())
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)
All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.