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 | |
---|---|
r | I will open a file in read-only mode. This is the default mode. |
x | Used only for the exclusive creation. If throws an error, if file already exists. |
w | To create and write to file. If a file already exists, it will truncate the existing file. |
a | It will append the new content to the existing file. |
d | It will create and open a binary file. |
t | It will open the file in text mode. |
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()
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.