TechBeamersTechBeamers
  • Learn ProgrammingLearn Programming
    • Python Programming
      • Python Basic
      • Python OOP
      • Python Pandas
      • Python PIP
      • Python Advanced
      • Python Selenium
    • Python Examples
    • Selenium Tutorials
      • Selenium with Java
      • Selenium with Python
    • Software Testing Tutorials
    • Java Programming
      • Java Basic
      • Java Flow Control
      • Java OOP
    • C Programming
    • Linux Commands
    • MySQL Commands
    • Agile in Software
    • AngularJS Guides
    • Android Tutorials
  • Interview PrepInterview Prep
    • SQL Interview Questions
    • Testing Interview Q&A
    • Python Interview Q&A
    • Selenium Interview Q&A
    • C Sharp Interview Q&A
    • PHP Interview Questions
    • Java Interview Questions
    • Web Development Q&A
  • Self AssessmentSelf Assessment
    • Python Test
    • Java Online Test
    • Selenium Quiz
    • Testing Quiz
    • HTML CSS Quiz
    • Shell Script Test
    • C/C++ Coding Test
Search
  • Python Multiline String
  • Python Multiline Comment
  • Python Iterate String
  • Python Dictionary
  • Python Lists
  • Python List Contains
  • Page Object Model
  • TestNG Annotations
  • Python Function Quiz
  • Python String Quiz
  • Python OOP Test
  • Java Spring Test
  • Java Collection Quiz
  • JavaScript Skill Test
  • Selenium Skill Test
  • Selenium Python Quiz
  • Shell Scripting Test
  • Latest Python Q&A
  • CSharp Coding Q&A
  • SQL Query Question
  • Top Selenium Q&A
  • Top QA Questions
  • Latest Testing Q&A
  • REST API Questions
  • Linux Interview Q&A
  • Shell Script Questions
© 2024 TechBeamers. All Rights Reserved.
Reading: Read File Line by Line in Python
Font ResizerAa
TechBeamersTechBeamers
Font ResizerAa
  • Python
  • SQL
  • C
  • Java
  • Testing
  • Selenium
  • Agile Concepts Simplified
  • Linux
  • MySQL
  • Python Quizzes
  • Java Quiz
  • Testing Quiz
  • Shell Script Quiz
  • WebDev Interview
  • Python Basic
  • Python Examples
  • Python Advanced
  • Python OOP
  • Python Selenium
  • General Tech
Search
  • Programming Tutorials
    • Python Tutorial
    • Python Examples
    • Java Tutorial
    • C Tutorial
    • MySQL Tutorial
    • Selenium Tutorial
    • Testing Tutorial
  • Top Interview Q&A
    • SQL Interview
    • Web Dev Interview
  • Best Coding Quiz
    • Python Quizzes
    • Java Quiz
    • Testing Quiz
    • ShellScript Quiz
Follow US
© 2024 TechBeamers. All Rights Reserved.
Python BasicPython Tutorials

Read File Line by Line in Python

Last updated: Oct 23, 2023 8:56 am
By Meenakshi Agarwal
Share
7 Min Read
python read file line by line techniques
SHARE

In this tutorial, we’ll describe multiple ways in Python to read a file line by line with examples such as using readlines(), context manager, while loops, etc. After this, you can adopt one of these methods in your projects that fits the best as per the conditions.

Contents
Readlines() to read all lines togetherExampleReadline() to read file line by lineExampleReading files using Python context managerExample

Python has made File I/O super easy for programmers. However, it is for you to decide what’s the most efficient technique for your situation. It would depend on many parameters, such as the frequency of such an operation, the size of the file, etc.

Let’s assume we have a logs.txt file that resides in the same folder along with the Python script.

Various Techniques to Read a File Line by Line in Python

We’ll now go over each method to read a file line by line.

python read file line by line techniques

Readlines() to read all lines together

We recommend this solution for files with a smaller size. If the file size is large, then it becomes inefficient as it loads the entire file in memory.

However, when the file is small, it is easier to load and parse the content line by line.

The readlines() returns a sequence of all lines from the file each containing a newline char except the last one.

We’ve demonstrated the use of readlines() function in the below example. Here, you can see that we are also using the Python while loop to traverse the lines.

Example

"""
 Example:
 Using readlines() to read all lines in a file
"""

ListOfLines = ["Python", "CSharp", "PHP", "JavaScript", "AngularJS"]

# Function to create our test file
def createFile():
    wr = open("Logs.txt", "w")
    for line in ListOfLines:
      # write all lines
      wr.write(line)
      wr.write("\n")
    wr.close()

# Function to demo the readlines() function
def readFile():
    rd = open ("Logs.txt", "r")

    # Read list of lines
    out = rd.readlines()
     
    # Close file 
    rd.close()
    
    return out

# Main test
def main():
    
    # create Logs.txt
    createFile()
    
    # read lines from Logs.txt
    outList = readFile()
    
    # Iterate over the lines
    for line in outList:
        print(line.strip())    

# Run Test
if __name__ == "__main__":
    main()

The output is as follows:

Python
CSharp
PHP
JavaScript
AngularJS

On the other hand, the above solution will cause high memory usage for large files. So, you should choose a different approach.

For instance, you may like to try this one.

Check this: Loop Through Files in a Directory

Readline() to read file line by line

When the file size reaches MBs or GB, the right idea is to fetch one line at a time. Python readline() method does this job efficiently. It does not load all data in one go.

The readline() reads the text until the newline character and returns the line. It handles the EOF (end of file) by returning a blank string.

Example

"""
 Example:
 Using readline() to read a file line by line in Python
"""

ListOfLines = ["Tesla", "Ram", "GMC", "Chrysler", "Chevrolet"]

# Function to create our test file
def createFile():
    wr = open("Logs.txt", "w")
    for line in ListOfLines:
      # write all lines
      wr.write(line)
      wr.write("\n")
    wr.close()

# Function to demo the readlines() function
def readFile():
    rd = open ("Logs.txt", "r")

    # Read list of lines
    out = [] # list to save lines
    while True:
        # Read next line
        line = rd.readline()
        # If line is blank, then you struck the EOF
        if not line :
            break;
        out.append(line.strip())
     
    # Close file 
    rd.close()
    
    return out

# Main test
def main():
    
    # create Logs.txt
    createFile()
    
    # read lines from Logs.txt
    outList = readFile()
    
    # Iterate over the lines
    for line in outList:
        print(line.strip())    

# Run Test
if __name__ == "__main__":
    main()

After execution, the output is:

Tesla
Ram
GMC
Chrysler
Chevrolet

Reading files using Python context manager

Python provides a concept of context managers. It involves using the “with” clause with the File I/O functions. It keeps track of the open file and closes it automatically after the file operation ends.

Hence, we can confirm that you never miss closing a file handle using the context manager. It performs cleanup tasks like closing a file accordingly.

In the below example, you can see that we are using the context manager (with) along with the Python for loop to first write and then read lines.

Example

"""
 Example:
 Using context manager and for loop read a file line by line
"""

ListOfLines = ["NumPy", "Theano", "Keras", "PyTorch", "SciPy"]

# Function to create test log using context manager
def createFile():
    with open ("testLog.txt", "w") as wr:
        for line in ListOfLines:
            # write all lines
            wr.write(line)
            wr.write("\n")

# Function to read test log using context manager
def readFile():
    rd = open ("testLog.txt", "r")

    # Read list of lines
    out = [] # list to save lines
    with open ("testLog.txt", "r") as rd:
        # Read lines in loop
        for line in rd:
            # All lines (besides the last) will include  newline, so strip it
            out.append(line.strip())

    return out

# Main test
def main():
    
    # create testLog.txt
    createFile()
    
    # read lines from testLog.txt
    outList = readFile()
    
    # Iterate over the lines
    for line in outList:
        print(line.strip())    

# Run Test
if __name__ == "__main__":
    main()

After running the code snippet, the output is:

NumPy
Theano
Keras
PyTorch
SciPy

To learn more about File I/O, read our tutorial on Python file handling.

You Might Also Like

How to Connect to PostgreSQL in Python

Generate Random IP Address (IPv4/IPv6) in Python

Python Remove Elements from a List

How to Use Extent Report in Python

10 Python Tricky Coding Exercises

Meenakshi Agarwal Avatar
By Meenakshi Agarwal
Follow:
Hi, I'm Meenakshi Agarwal. I have a Bachelor's degree in Computer Science and a Master's degree in Computer Applications. After spending over a decade in large MNCs, I gained extensive experience in programming, coding, software development, testing, and automation. Now, I share my knowledge through tutorials, quizzes, and interview questions on Python, Java, Selenium, SQL, and C# on my blog, TechBeamers.com.
Previous Article MySQL tutorial for the starters MySQL Tutorial for Beginners to Learn SQL
Next Article Crack Java Interview Easily How to Crack a Java Interview Easily?

Popular Tutorials

SQL Interview Questions List
50 SQL Practice Questions for Good Results in Interview
SQL Interview Nov 01, 2016
Demo Websites You Need to Practice Selenium
7 Sites to Practice Selenium for Free in 2024
Selenium Tutorial Feb 08, 2016
SQL Exercises with Sample Table and Demo Data
SQL Exercises – Complex Queries
SQL Interview May 10, 2020
Java Coding Questions for Software Testers
15 Java Coding Questions for Testers
Selenium Tutorial Jun 17, 2016
30 Quick Python Programming Questions On List, Tuple & Dictionary
30 Python Programming Questions On List, Tuple, and Dictionary
Python Basic Python Tutorials Oct 07, 2016
//
Our tutorials are written by real people who’ve put in the time to research and test thoroughly. Whether you’re a beginner or a pro, our tutorials will guide you through everything you need to learn a programming language.

Top Coding Tips

  • PYTHON TIPS
  • PANDAS TIPSNew
  • DATA ANALYSIS TIPS
  • SELENIUM TIPS
  • C CODING TIPS
  • GDB DEBUG TIPS
  • SQL TIPS & TRICKS

Top Tutorials

  • PYTHON TUTORIAL FOR BEGINNERS
  • SELENIUM WEBDRIVER TUTORIAL
  • SELENIUM PYTHON TUTORIAL
  • SELENIUM DEMO WEBSITESHot
  • TESTNG TUTORIALS FOR BEGINNERS
  • PYTHON MULTITHREADING TUTORIAL
  • JAVA MULTITHREADING TUTORIAL

Sign Up for Our Newsletter

Subscribe to our newsletter to get our newest articles instantly!

Loading
TechBeamersTechBeamers
Follow US
© 2024 TechBeamers. All Rights Reserved.
  • About
  • Contact
  • Disclaimer
  • Privacy Policy
  • Terms of Use
TechBeamers Newsletter - Subscribe for Latest Updates
Join Us!

Subscribe to our newsletter and never miss the latest tech tutorials, quizzes, and tips.

Loading
Zero spam, Unsubscribe at any time.
x