Python open() is an inbuilt function that opens the file and returns it as a file object. It is used in the file handling process. Python open() function returns the file object which can be used to read, write, and modify the file. If a file is not found, then it raises the FileNotFoundError exception.
The syntax of the open() function is the following.
open(file, mode)
file: This parameter as the name suggests, is the name of the file that we want to open.
mode: This parameter is a string that is used to specify the mode in which the file is to be opened. The following strings can be used to activate a specific mode:
“a” – Append – Opens the file for appending, creates the file if it does not exist.
“w” – Write – Opens the file for writing, creates a file if it does not exist.
“x” – Create – Creates a specified file, returns an error if the file exists.
Also, you can specify if a file should be handled as binary or text mode.
“t” – Text – Default value. Text mode.
“b” – Binary – Binary mode (e.g. images).
Example 1
The below example shows how to open a file in Python.
# opens python.text file of the current directory
f = open("python.txt")
# specifying full path
f = open("C:/Python33/README.txt")
Output:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
Example 2
The below example providing mode to open().
# file opens for read
f = open("path_to_file", mode='r')
# file opens for write
f = open("path_to_file", mode = 'w')
# file opens for writing to the end
f = open("path_to_file", mode = 'a')
Output:
f = open("path_to_file", mode = 'r', encoding='utf-8')
In the above example, we specify different modes('r', 'w', 'a') for opening a file.
#python #python open #filenotfounderror