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.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
Example 1:
# opens test.text file of the current directory
f = open("test.txt")
# specifying the full path
f = open("C:/Python33/README.txt")
Since the mode is omitted, the file is opened in
'r'
mode; opens for reading.
Example 2:
# 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