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

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

where

Parameter Required/Optional Description
file Required A string. Path and name of file.
mode Optional A 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)
buffering Optional An integer. Buffering policy.0 – switch buffering off (in binary mode)1 – line buffering (in text mode)
encoding Optional A string. Name of encoding used to decode or encode the file.
errors Optional A string. Specifies how encoding and decoding errors are to be handled.
newline Optional A string. Specifies how newlines mode words.Possible values are ”, ‘\n’, ‘\r’ and ‘\r\n’. Default value is None.
closefd Optional Boolean value. Specifies whether file descriptor is to be closed.
opener Optional

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

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

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.