Open
On this page
Introduction
Opening a file is an essential operation when you need to perform other file operations, such as read, write, or append. This Python glossary entry focuses on the open
function in Python and how you can use it to perform various file operations.
Syntax
Below is the standard syntax of the open
function in Python:
The open
function accepts two parameters:
file
: This specifies the name of the file that you want to open.mode
: This indicates the mode in which the file should be opened.
There are several modes in Python you can use to open a file:
'r'
: Open a file for reading.'w'
: Open a file for writing.'a'
: Open a file for appending.'x'
: Open a file for exclusive creation.'b'
: Open a file in binary mode.'t'
: Open a file in text mode.
The ‘r’, ‘w’, and ‘a’ modes can be combined with ‘b’ or ’t’ to make it either a binary or a text mode. By default, a file is opened in ’t’ mode with the ‘r’ or ‘r+’ access.
Example
Let’s open a file named sample.txt
in read mode:
This will open sample.txt
in read mode and the file operations can be performed on the file object file
.
Did you know?
In Python, if the file mentioned is not present on the system, and we are trying to read it, an error will be raised. But if we are trying to write or append, Python will create a new file.
You can then perform subsequent file operations using the obtained file object, do remember to close the file after operations to free up system resources.