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 : 

Leave a Reply

Your email address will not be published. Required fields are marked *