Python Script to Read Files Line by Line Using ReadLine and ReadLines Method Full Project For Beginners

Python Script to Read Files Line by Line Using ReadLine and ReadLines Method Full Project For Beginners

 

Welcome folks today in this blog post we will be reading files line by line using the readline and readlines method. All the full source code of the application is given below.

 

 

 

Get Started

 

 

 

In order to get started you need to be having python installed on your computer. After that we will making a file inside the root directory called as myfile.txt and copy paste the following code

 

 

 

myfile.txt

 

 

 

delhi
gujarat
pune
mumbai
jammu
kashmir
jaipur

 

 

Now create an app.py file and copy paste the following code

 

 

app.py

 

 

# Using readlines() 
file1 = open('myfile.txt', 'r') 
Lines = file1.readlines() 
  
count = 0
# Strips the newline character 
for line in Lines: 
    print("Line{}: {}".format(count, line.strip()))

 

 

Here we are using the readlines method to read all the lines present inside the myfile.txt file and you can see the following result if you run the file

READ  Python 3 Script to Find Second Largest Element in an Array or List Using Sort() Method Full Tutorial For Beginners

 

python app.py

 

 

 

 

 

Using Readline Method

 

 

 

Now we will doing the same process using the readline method so this method reads line by line the text written in text file

 

 

# Using readline() 
file1 = open('myfile.txt', 'r') 
count = 0
  
while True: 
    count += 1
  
    # Get next line from file 
    line = file1.readline() 
  
    # if line is empty 
    # end of file is reached 
    if not line: 
        break
    print("Line{}: {}".format(count, line.strip())) 
  
file1.close()

 

 

 

 

 

Leave a Reply