Python Program to Get the Line Count of a File – 2024

Hey guys, in this blog we will see a Python Program to Get the Line Count of a File.

The content of the file my_file.txt is

Machine Learning Projects
Deep Learning Projects
Computer Vision Projects

Example 1: Using a for loop

def file_len(fname):
    with open(fname) as f:
        for i, l in enumerate(f):
            pass
    return i + 1

print(file_len("my_file.txt"))

Output

3

  • Here we have just opened the file and used enumerate to count the number of lines in the file and then returned i+1.
  • We just started a for-loop and we are not performing any function in it.

Example 2: Using list comprehension

num_of_lines = sum(1 for l in open('my_file.txt'))

print(num_of_lines)

Output

3

  • Here also opened the file and calculated the number of lines.
  • The first line in the code says that for each found line in the code, add a 1 in our tuple and will create a result like sum(1,1,1) which is equal to 3.

Check out our other python programming examples

Leave a Reply

Your email address will not be published. Required fields are marked *