HappiomHappiom
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
  • Self-Improvement
  • Relationship
  • AI for Life
  • Apps
  • Tech
  • More
    • Online Diary
    • Glossary
  • Learn
    • Book
    • >> Soft Skills
    • Time Management
    • >> Tech Skills
    • R
    • Linux
    • Python
  • Our Apps
    • Download Diary App
    • Write Your First Diary
    • Login to Online Diary App
    • 100K+ Famous Quotes Site
  • Resources
    • Self-Improvement Guide
      • 21-Days to Self-Improvement
      • Creating a Habit
      • Learn Life Experiences
      • Easily Prioritizing Tasks
      • Learning from Mistakes
      • Doing Regular Exercises
      • Setting Priority for Success
      • Avoiding Common Mistakes
      • Eating Healthy Food Regularly
    • Journaling Guide
      • Online Diary
      • Best Diary Apps
      • Diary Writing Ideas
      • Diary Writing Topics
      • Avoid Writing in Diary
      • Diary Writing as Hobby
      • Reasons to Write a Diary
      • Types of Feelings In Diary
      • Improve Diary Writing Skills
Expand All Collapse All
  • Python Examples
    • Basic Syntax
      • Python Example Code to Concat 2 Numbers
      • Python Example Code to Concat N Strings
      • Python Code to Find Perimeter of a Circle
      • Python Code to Convert CSV file to Parquet format
      • Python Code to Get Current Day of Week
      • Python Code to Convert Binary String to Decimal Number Vice versa
      • Python Code to Find Difference Between 2 Strings
      • Python Example Code to Remove Duplicates from a List
      • Python Example Code to Calculate Height of Triangle
      • Python Code to Generate Complex Random Password
    • File Handling
      • Python Code to Write & Read Key Value Pair in File
      • In Python File is Not Opening (How to Fix)
      • Python Code to Read Specific Line from a File
      • Python Code to Clear Contents of a File
      • Python Code to Count and List Files in a Directory
    • Modules and Libraries
      • Python Code for Automation using BDD
      • Python Code to Load .SO File (and Invoke a Function)
    • Object-Oriented Programming
      • Python Code to Create a Class with Attributes
      • Python Code to Define Methods in a Class
    • Python Example Code to Check Internet Connection
    • Example Python Code to Send an Email
    • Python Code to Fetch Data from an API (e.g., OpenWeatherMap)
    • Example Python Code to Extract Text from PDF
    • Python Code to Perform Web Scraping (e.g., Scraping Wikipedia)
    • Example Python Code to Plot Data Using Matplotlib
    • Python Code to Perform Data Analysis with Pandas
    • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
    • Python Code to Handle User Authentication in Flask
    • Example Python Code to interact with databases using libraries like SQLAlchemy

Python Code to Read Specific Line from a File

Let’s quick see about reading a particular line from a text file using Python. Whether you’re working with log files, data sets, or any other text-based resources, being able to extract specific lines programmatically is a valuable skill.

I will provide you with a Python function that efficiently reads the desired line from a file and explain how you can use it effectively in your projects.

Method 1 – Using readlines() function

Below is the simple method using readlines() function.

def read_specific_line(file_path, line_number):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        if 0 < line_number <= len(lines):
            return lines[line_number - 1]
        else:
            return "Line number out of range"

The following shows example usage demonstrates how to call this function with a file path and a line number to read a specific line from the file:

file_path = 'example.txt'  # Replace 'example.txt' with your file path
line_number = 5  # Replace 5 with the line number you want to read
line = read_specific_line(file_path, line_number)
print("Line {}: {}".format(line_number, line.strip()))

In this example,

  • read_specific_line function takes two arguments: file_path (the path to the file) and line_number (the line number you want to read).
  • It opens the file specified by file_path in read mode.
  • It reads all lines into a list using readlines() method.
  • It checks if the specified line_number is within the range of lines in the file.
  • If the line number is valid, it returns the line at that position (zero-based index is converted to one-based).
  • If the line number is out of range, it returns a message indicating that.

Method 2 – Using if condition and looping

Let’s another method which loops through the file and locates the specific line.

def read_specific_line_alternative(file_path, line_number):
    try:
        with open(file_path, 'r') as file:
            for current_line_number, line in enumerate(file, start=1):
                if current_line_number == line_number:
                    return line.strip()
            return f"Line {line_number} not found"
    except Exception as e:
        return f"Error reading line: {e}"

Let’s see how to use the above written function:

# usage of the read_specific_line_alternative function
file_path = "example.txt"
line_number = 5

line_content = read_specific_line_alternative(file_path, line_number)
print(f"Line {line_number}: {line_content}")

 

Let me explain the above code in detail,

  • We open the file using the open() function in read mode (‘r’) within a with statement to ensure that the file is properly closed after reading.
  • We use a for loop to iterate through each line in the file. The enumerate() function is used to get both the line content and the line number simultaneously, starting from 1.
  • Inside the loop, we check if the current line number matches the desired line number. If they match, we return the content of that line after stripping any leading or trailing whitespace.
  • If the loop completes without finding the desired line number, we return a message indicating that the line was not found.
  • Any errors that occur during the process are caught and an appropriate error message is returned.

This method provides an alternative approach that can be useful, especially for larger files where using linecache may not be the most efficient solution.

Reading specific lines from line is one of the most common operation required when you work on any projects that involve file operation to store large amount of data.

Related Articles
  • Python Example Code to Calculate Height of Triangle
  • Python Example Code to Remove Duplicates from a List
  • Example Python Code to interact with databases using libraries like SQLAlchemy
  • Python Code to Handle User Authentication in Flask
  • Example Python Code to Train a Simple Machine Learning Model (e.g., Linear Regression)
  • Python Code to Perform Data Analysis with Pandas

No luck finding what you need? Contact Us

Previously
In Python File is Not Opening (How to Fix)
Up Next
Python Code to Clear Contents of a File
  • About Us
  • Contact Us
  • Archive
  • Hindi
  • Tamil
  • Telugu
  • Marathi
  • Gujarati
  • Malayalam
  • Kannada
  • Privacy Policy
  • Copyright 2026 Happiom. All Rights Reserved.