The syntax of open() is:
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)
'r'(open for reading in text mode). Available file modes are:
|'r'||Open a file for reading. (default)|
|'w'||Open a file for writing. Creates a new file if it does not exist or truncates the file if it exists.|
|'x'||Open a file for exclusive creation. If the file already exists, the operation fails.|
|'a'||Open for appending at the end of the file without truncating it. Creates a new file if it does not exist.|
|'t'||Open in text mode. (default)|
|'b'||Open in binary mode.|
|'+'||Open a file for updating (reading and writing)|
True(default) if given otherwise an exception will be raised
The open() function returns a file object which can used to read, write and modify file.
If the file is not found, it raises
# opens test.text file of the current directory f = open("test.txt") # specifying full path f = open("C:/Python33/README.txt")
Since the mode is omitted, the file is opened in
'r' mode; opens for reading.
# opens for read f = open("path_to_file", mode='r') # opens for write f = open("path_to_file", mode = 'w') # opens for writing to the end f = open("path_to_file", mode = 'a')
Python has a encoding system which is platform dependent.Hence, it's recommended to specify the encoding type if you are working in a text mode.
f = open("path_to_file", mode = 'r', encoding='utf-8')
Recommended Reading: Python File I/O