Python read file line by line

Python File Reading line by line

How to Read a file in Python?

Before Program python file read line by line ,first we need to understand the file basic operation , to know more about this ,click here.

Once we understood the basic file operations ,we need to look the reading operations of file.

The read operation can be performed in two ways:

one is through read() and another one is through readlines().

The following program illustrate this:

file1 = open('myfile.txt', 'w')
file1.write("Helloword \n")
file1.close()
# Using readlines()
file1 = open('myfile.txt', 'r')
Lines = file1.readlines()
print Lines  
 

The above code explains the concept reading the file line by line.

We will look into the program line by line .

First we create a file called myfile.txt in write mode,

after creating we enter the text as Helloworld into the file.

Then we close the fie. 

Then agina ,we reopen the file in read mode , this time we use the readlines function to read the file content line by line.

The redline can take the argument but it is optional, we can specify the which line we need to read.

 

 

 

Scroll to Top