Python open()

Python open() builtin function is used to open a file in specified mode and return the file object. We may use the file object to perform required file operations.

In this tutorial, we will learn about the syntax of Python open() function, and learn how to use this function with the help of examples.

Syntax

The syntax of open() function is

</>
Copy
open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

where

ParameterRequired/
Optional
Description
fileRequiredA string. Path and name of file.
modeOptionalA string. Defines which mode the file is to be opened.
The following are possible values, and description.
‘r’ – read file
‘a’ – append to file
‘w’ – write to file
‘x’ – create file
‘t’ – text mode
‘b’ – binary mode
‘+’ – updating (read and write)
bufferingOptionalAn integer. Buffering policy.
0 – switch buffering off (in binary mode)
1 – line buffering (in text mode)
encodingOptionalA string. Name of encoding used to decode or encode the file.
errorsOptionalA string. Specifies how encoding and decoding errors are to be handled.
newlineOptionalA string. Specifies how newlines mode words.
Possible values are ”, ‘\n’, ‘\r’ and ‘\r\n’. Default value is None.
closefdOptionalBoolean value. Specifies whether file descriptor is to be closed.
openerOptional

Returns

The function returns file object.

Examples

1. Open and Read File

In this example, we open a file 'sample.txt' in read mode and read its content.

Python Program

</>
Copy
f = open('sample.txt')
content = f.read()
print(content)

Output

Hello World

2. Open and Append to File

In this example, we open a file 'sample.txt' in append mode using open() function and append 'foo bar' to the existing content with the help of file.write() method.

Python Program

</>
Copy
f = open('sample.txt', mode='a')
f.write('foo bar')

sample.txt

Hello Worldfoo bar

Conclusion

In this Python Tutorial, we have learnt the syntax of Python open() builtin function, and also learned how to use this function, with the help of Python example programs.