Python open() Function
Opens a file for reading, writing or appending.
Syntax
Python
Copy Code
open(file, mode, buffering, encoding = None, errors = None, newline = None, closefd = False, opener = None)
Parameters
Parameter | Description |
---|---|
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
|
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.
Example
Python
Copy Code
file = open('myFile.txt', 'w') file.write('Python is great!') file.close(); file = open('myFile.txt', 'r') print(file.read()) file.close()
Output
Python is great!