Open a File in Python


Open a file

To open a file in python, use the built-in open() function. The open function returns the file object, which can be used to perform operations on the file.

It is always good practice to close the file, once we are done with our work. Use filename.close() method for that.

Syntax

In [ ]:
file_object_name = open('filename','access_mode')

Access Modes

We can use the below access modes to open a file.

Mode
rI will open a file in read-only mode. This is the default mode.
xUsed only for the exclusive creation. If throws an error, if file already exists.
wTo create and write to file. If a file already exists, it will truncate the existing file.
aIt will append the new content to the existing file.
dIt will create and open a binary file.
tIt will open the file in text mode.
File modes

Open a file in read-only mode

We can use the access mode as ‘r’ to open the file in read-only mode. As read-only is the default mode, so we need not mention this while opening file.

Example:

In [1]:
file= open("readme.txt",'r')
print(file.read())
file.close()
Welcome to Logical Python

Difference between WRITE mode and APPEND mode

If we open the file in the write mode and the file already exists, then it will truncate the existing file. In case we use the append mode, then it will append new content to an existing file.