Python count number lines

How to count the number of lines, words, and characters in Python

Many candidates are rejected or down-leveled in technical interviews due to poor performance in behavioral or cultural fit interviews. Ace your interviews with this free course, where you will practice confidently tackling behavioral interview questions.

In this Answer, we’ll learn to count the number of lines, words, and characters present in a file.

The basic idea is to traverse each line in a file and count the number of words and characters.

Code example

Let’s take a look at the following example:

number_of_words = 0
number_of_lines = 0
number_of_characters = 0
with open("data.txt", 'r') as file:
for l in file:
number_of_words += len(l.split())
number_of_lines += 1
number_of_characters = len(l)
print("No of words: ", number_of_words)
print("No of lines: ", number_of_lines)
print("No of characters: ", number_of_characters)

Code explanation

In the above code snippet:

  • Lines 1–4: We declare and initialize variables with value 0 to store the total count of words, characters, and lines.
  • Line 5: We open the file in reading mode r .
  • Line 6: We loop through each line in the file using the for loop.
  • Line 7: We get the list of words present in a line using the split() method. We calculate the length/number of words passing the result of the split() method to the len() function and add it to the number_of_words variable.
  • Line 8: We add value 1 to number_of_lines variable as we progress through each line in a file.
  • Line 9: We get the count of characters using the len() function and add the result to the number_of_characters variable.

Once we traverse each line in a file, we get the count of lines, words, and characters present in a file.

Learn in-demand tech skills in half the time

Источник

Python Count Number of Lines in a File

If the file is significantly large (in GB), and you don’t want to read the whole file to get the line count, This article lets you know how to get the count of lines present in a file in Python.

Table of contents

Steps to Get Line Count in a File

Count Number of Lines in a text File in Python

  1. Open file in Read Mode To open a file pass file path and access mode r to the open() function.
    For example, fp= open(r’File_Path’, ‘r’) to read a file.
  2. Use for loop with enumerate() function to get a line and its number. The enumerate() function adds a counter to an iterable and returns it in enumerate object. Pass the file pointer returned by the open() function to the enumerate() . The enumerate() function adds a counter to each line.
    We can use this enumerate object with a loop to access the line number. Return counter when the line ends.
  3. Close file after completing the read operation We need to make sure that the file will be closed properly after completing the file operation. Use fp.close() to close a file.
Читайте также:  About jquery in html

Consider a file “read_demo.txt.” See an image to view the file’s content for reference.

text file

# open file in read mode with open(r"E:\demos\files\read_demo.txt", 'r') as fp: for count, line in enumerate(fp): pass print('Total Lines', count + 1)
  • The enumerate() function adds a counter to each line.
  • Using enumerate, we are not using unnecessary memory. It is helpful if the file size is large.
  • Note: enumerate(file_pointer) doesn’t load the entire file in memory, so this is an efficient fasted way to count lines in a file.

Generator and Raw Interface to get Line Count

A fast and compact solution to getting line count could be a generator expression. If the file contains a vast number of lines (like file size in GB), you should use the generator for speed.

This solution accepts file pointer and line count. To get a faster solution, use the unbuffered (raw) interface, using byte arrays, and making your own buffering.

def _count_generator(reader): b = reader(1024 * 1024) while b: yield b b = reader(1024 * 1024) with open(r'E:\demos\files\read_demo.txt', 'rb') as fp: c_generator = _count_generator(fp.raw.read) # count each \n count = sum(buffer.count(b'\n') for buffer in c_generator) print('Total lines:', count + 1)

Use readlines() to get Line Count

If your file size is small and you are not concerned with performance, then the readlines() method is best suited.

This is the most straightforward way to count the number of lines in a text file in Python.

  • The readlines() method reads all lines from a file and stores it in a list.
  • Next, use the len() function to find the length of the list which is nothing but total lines present in a file.

Open a file and use the readlines() method on file pointer to read all lines.

with open(r"E:\demos\files\read_demo.txt", 'r') as fp: x = len(fp.readlines()) print('Total lines:', x) # 8

Note: This isn’t memory-efficient because it loads the entire file in memory. It is the most significant disadvantage if you are working with large files whose size is in GB.

Use Loop and Sum Function to Count Lines

You can use the for loop to read each line and pass for loop to sum function to get the total iteration count which is nothing but a line count.

with open(r"E:\demos\files\read_demo.txt", 'r') as fp: num_lines = sum(1 for line in fp) print('Total lines:', num_lines) # 8

If you want to exclude the empty lines count use the below example.

with open(r"E:\demos\files\read_demo.txt", 'r') as fp: num_lines = sum(1 for line in fp if line.rstrip()) print('Total lines:', num_lines) # 8

The in Operator and Loop to get Line Count

Using in operator and loop, we can get a line count of nonempty lines in the file.

  • Set counter to zero
  • Use a for-loop to read each line of a file, and if the line is nonempty, increase line count by 1
# open file in read mode with open(r"E:\demos\files_demos\read_demo.txt", 'r') as fp: count = 0 for line in fp: if line != "\n": count += 1 print('Total Lines', count)

Count number of lines in a file Excluding Blank Lines

For example, below is the text file which uses the blank lines used to separate blocks.

Jessa = 70 Kelly = 80 Roy = 90 Emma = 25 Nat = 80 Sam = 75

When we use all the above approaches, they also count the blank lines. In this example, we will see how to count the number of lines in a file, excluding blank lines

count = 0 with open('read_demo.txt') as fp: for line in fp: if line.strip(): count += 1 print('number of non-blank lines', count)
number of non-blank lines 6

Conclusion

  • Use readlines() or A loop solution if the file size is small.
  • Use Generator and Raw interface to get line count if you are working with large files.
  • Use a loop and enumerate() for large files because we don’t need to load the entire file in memory.
Читайте также:  Java terminal run jar

Did you find this page helpful? Let others know about it. Sharing helps me continue to create free Python resources.

About Vishal

I’m Vishal Hule, Founder of PYnative.com. I am a Python developer, and I love to write articles to help students, developers, and learners. Follow me on Twitter

Python Exercises and Quizzes

Free coding exercises and quizzes cover Python basics, data structure, data analytics, and more.

  • 15+ Topic-specific Exercises and Quizzes
  • Each Exercise contains 10 questions
  • Each Quiz contains 12-15 MCQ

Источник

Number of Lines in a File in Python

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) 
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)
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)
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.

Читайте также:  Xlwt python 3 документация

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.

Источник

How to count the number of lines in a text file in Python

In order to learn how to count the number of lines in a text file in Python, you have to understand the open() function in Python. In this tutorial, we will learn to count the number of lines in text files using Python.

If you already have a basic understanding of the Python open() function, then let’s follow this tutorial…

Text files can be used in many situations. For example, you may save your in a text file or you may fetch the data of a text file in Python. In my previous tutorial, I have shown you how to create a text file in Python.

Now in this article, I will show you how to count the total number of lines in a text file.

In order to open a file, we need to use the open() function.

Count the number of lines in a text file in Python

We can reach our aim with various techniques. Some of those can only deal with small to medium size text files and some techniques are able to handle large files.

Here I am going to provide both of these techniques so that you can use the perfect one for you.

Assume that you have a text file in the same directory with the filename: this_is_file.txt . Suppose, this file contains the given text content that you can see below:

Hello I am first line I am the 2nd line I am oviously 3rd line

To get the number of lines in our text file below is the given Python program:

number_of_lines = len(open('this_is_file.txt').readlines( )) print(number_of_lines)

Special Note: It can not deal with very large files. But it will work fine on small to medium size files

Count number of lines in a text file of large size

To handle large-size text file you can use the following Python program:

with open('this_is_file.txt') as my_file: print(sum(1 for _ in my_file))

If you have any doubts or suggestions you can simply write in the below comment section

Источник

Оцените статью