• Skip to primary navigation
  • Skip to main content
  • Skip to primary sidebar
PythonForBeginners.com

PythonForBeginners.com

Learn By Example

  • Home
  • Learn Python
    • Python Tutorial
  • Categories
    • Basics
    • Lists
    • Dictionary
    • Code Snippets
    • Comments
    • Modules
    • API
    • Beautiful Soup
    • Cheatsheet
    • Games
    • Loops
  • Python Courses
    • Python 3 For Beginners
You are here: Home / Basics / Number of Lines in a File in Python

Number of Lines in a File in Python

Author: Aditya Raj
Last Updated: February 18, 2022

File handling is one of the most critical operations in programming. Sometimes, we may need to count the number of lines in a file to perform any operation on it. In this article, we will see how we can count the number of lines in a file in python. 

Count Number of Lines in a File using the for loop in Python

The first way to count the number of lines in a file is to use a for loop to count all the newline characters in the file. 

For this, we will first open the file using the open() function in the read mode. After that, we will traverse through the file content and check for the newline character “\n”. We will keep the count of “\n” characters in a variable named numberOfLines.

After execution of the for loop, we will have the total number of lines in the variable numberOfLines. You can observe this in the following example.

myFile = open("sample.txt", "r")
text = myFile.read()
print("The content of the file is:")
print(text)
numberOfLines = 0
for character in text:
    if character == "\n":
        numberOfLines = numberOfLines + 1
print("The number of lines in the file is:")
print(numberOfLines)

Output:

The content of the file is:
This is line 1.
This is line 2.
This is line 3.
This is line 4.

The number of lines in the file is:
4

While counting the number number of lines, empty lines are also counted in this method. This is so because we are counting the newline characters. Hence, empty lines will also be considered a new line as the “\n” character is present there.

Count Number of Lines in a File using the split() method in Python

Instead of checking for newline characters, we can use the split() method to count the number of lines in  a file. The split() method, when invoked on a string, takes a separator as input argument and returns a list of substrings of the original string. 

In our program, we will use “\n” as the separator to split the text of the file at newlines. After that, we will determine the length of the output list using the len() function. In this way, we will find the number of lines in the text file.

myFile = open("sample.txt", "r")
text = myFile.read()
print("The content of the file is:")
print(text)
text_list = text.split("\n")
numberOfLines = len(text_list)
print("The number of lines in the file is:")
print(numberOfLines)

Output:

The content of the file is:
This is line 1.
This is line 2.
This is line 3.
This is line 4.
The number of lines in the file is:
4

Count Number of Lines in a File using the readlines() method in Python

The readlines() method, when invoked on a file object, returns a list of strings in the file. Each string consists of a newline. We can find the length of the output list to count the number of lines in the file as follows.

myFile = open("sample.txt", "r")
text_list = myFile.readlines()
numberOfLines = len(text_list)
print("The number of lines in the file is:")
print(numberOfLines)

Output:

The number of lines in the file is:
4

Conclusion

In this article, we have discussed three ways to count the number of lines in a file in python. To read more about files, you can read this article on file handling in python. You might also like this article on how to read a text file line by line in python.

Related

Recommended Python Training

Course: Python 3 For Beginners

Over 15 hours of video content with guided instruction for beginners. Learn how to create real world applications and master the basics.

Enroll Now

Filed Under: Basics Author: Aditya Raj

More Python Topics

API Argv Basics Beautiful Soup Cheatsheet Code Code Snippets Command Line Comments Concatenation crawler Data Structures Data Types deque Development Dictionary Dictionary Data Structure In Python Error Handling Exceptions Filehandling Files Functions Games GUI Json Lists Loops Mechanzie Modules Modules In Python Mysql OS pip Pyspark Python Python On The Web Python Strings Queue Requests Scraping Scripts Split Strings System & OS urllib2

Primary Sidebar

Menu

  • Basics
  • Cheatsheet
  • Code Snippets
  • Development
  • Dictionary
  • Error Handling
  • Lists
  • Loops
  • Modules
  • Scripts
  • Strings
  • System & OS
  • Web

Get Our Free Guide To Learning Python

Most Popular Content

  • Reading and Writing Files in Python
  • Python Dictionary – How To Create Dictionaries In Python
  • How to use Split in Python
  • Python String Concatenation and Formatting
  • List Comprehension in Python
  • How to Use sys.argv in Python?
  • How to use comments in Python
  • Try and Except in Python

Recent Posts

  • Count Rows With Null Values in PySpark
  • PySpark OrderBy One or Multiple Columns
  • Select Rows with Null values in PySpark
  • PySpark Count Distinct Values in One or Multiple Columns
  • PySpark Filter Rows in a DataFrame by Condition

Copyright © 2012–2025 · PythonForBeginners.com

  • Home
  • Contact Us
  • Privacy Policy
  • Write For Us