File Handling in Python
In this tutorial we are going to learn :
- Reading Text Files
- Close Files
Â
Â
Â
Reading Text FilesÂ
Â
- To read any files, we have to open the file first. We use the open() function to open file.
- open() method takes two-parameter ( file name – mode ). To read a file we use the r mode.
- There are two ways to open a file. The first one is located in the same folder and
the second one is located in a different location.
Â
Example :
This program opens a file from located in the same folder.

Â
Output of The Program :

Â
Â
Example :Â
This program opens a file from located in a different location.

Â
Output Of The Program :

Â
Â
Â
Example :Â
- To read the first line of the file, we use the readline() method.

Â
Output Of The Program :Â

Â
Â
Â
Example :Â
- We also read the file with for loop line by line.

Â
Output Of The Program :Â

Close Files
After open and do some tasks on file, we have to close the file. To close file we use the close() function.
Example :

Â
Output Of The Program :Â

Â
Â
Â
Example :Â
- Instead of closing files with the close() method , we can use the with method.
- This ensures that the file is closed when the block inside the with statement is exited.

Â
Output Of The Program :Â

