The built-in function open() is a good method for working with files. This method will check whether the file exists in the specified path, if yes it will return the file object otherwise it returns an error.
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None) #where file specifies the path
Takes 8 parameters in this one is required all the remaining are optional. In this mode type have many options(r: read, w: write, x: exclusive creation, a: appending, t: text mode, b: binary mode,+:updating(read,write))
Parameter | Description | Required / Optional |
---|---|---|
file | path-like object | Required |
mode | mode (optional) - mode while opening a file. If not provided, it defaults to 'r' | optional |
buffering | used for setting buffering policy | optional |
encoding | the encoding format | optional |
errors | a string specifying how to handle encoding/decoding errors | optional |
newline | how newlines mode works(available values: None, ' ', '\n', 'r', and '\r\n') | optional |
closefd | must be True (default); if given otherwise, an exception will be raised | optional |
opener | a custom opener; must return an open file descriptor | optional |
If the file exists in the specified path it will return a file object which can be used to read, write and modify. If the file does not exist, it raises the FileNotFoundError exception.
Input | Return Value |
---|---|
if file exist | file object |
# opens test.text file of the current directory
f = open("test.txt")
# specifying the full path
f = open("C:/Python33/README.txt")
Output:
Since the mode is omitted, the file is opened in 'r' mode; opens for reading.
# 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')
Output:
Open a file in read,write and append mode.