Read file line by line in python

Description

Python program to read a file line by line

Solution

file=open("sample.txt",'r')
content = file.readline()
while(content):
    print(content)
    content=file.readline()
file.close()

Explanation

open the file in read mode
read line by line using readline() method.
Read a line and check whether there is content in the line, then print it and read the next line. Repeat it until a line has no content.
close() the file.



Interesting Pattern Programs: for more Patterns

Input:
5
Output:
*
**
***
****
*****
****
***
**
*Solution
Input:
5
Output:
    *
   ***
  *****
 *******
*********
 *******
  *****
   ***
    *Solution
Input:
5
Output:
*        *
**      **
***    ***
****  ****
**********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********Solution
Input:
5
Output:
*       *
**     **
***   ***
**** ****
*********
**** ****
***   ***
**     **
*       *Solution
Input:
5
Output:
*********
 *******
  *****
   ***
    *
   ***
  *****
 *******
*********Solution

Related Programs