Python open() Function

Opens a file for reading, writing or appending.


open(file, mode, buffering, encoding = None, errors = None, newline = None, closefd = False, opener = None) 


file Required. A text or byte string indicating the location of the file to open, optionally including path info for files not in the current directory
mode Required. The mode with which to open the file. Possible values are

'r' open for reading (default)
'w' open for writing, truncating the file first
'x' create a new file and open it for writing. Using 'x' implies 'w'.
'a' open for writing, appending to the end of the file if it exists
'b' binary mode
't' text mode (default)
'+' open a disk file for updating (reading and writing)

buffering Optional. An integer representing the size of the buffer. 0 = no buffering (binary mode only), 1 = line buffering (text mode only). When no value is supplied the buffering size is determined automatically.
encoding Optional. The name of the encoding used to decode or encode the file. It should only be used in text mode. Default is None, which results in a platform dependent default being used.
errors Optional. A string that specifies how encoding errors are to be handled. This cannot be used in binary mode. Use 'strict' to raise a ValueError exception if there is an encoding error, or pass 'ignore' to ignore errors. Default is None, which implies 'strict'.
newlines Optional. A string that controls how universal newlines works. It only applies to text mode and can be None, '', '\n', '\r', and '\r\n'. Default is None
closefd Optional. If False, the underlying file descriptor will be kept open when the file is closed. This does not work when a file name is given (closefd must be True in this case)
opener Optional. A method that can be passed in order to retrieve the underlying file descriptor for the file object. Default is None

After one is done working with the file, the file should always be closed by calling the file object's close() method.


file = open('myFile.txt', 'w')
file.write('Python is great!')

file = open('myFile.txt', 'r')


Python is great!