Table of Contents
In this example, you will learn to get line count of a file.
To understand this example, you should have the knowledge of the following Python programming topics:
- Python enumerate()
- Python File I/O
- Python for Loop
1. Example 1: Using a for loop
The content of the file my_file.txt
is
honda 1948 mercedes 1926 ford 1903
Source Code
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
Using a for loop, the number of lines of a file can be counted.
- Open the file in read-only mode.
- Using a for loop, iterate through the object
f
. - In each iteration, a line is read; therefore, increase the value of loop variable after each iteration.
2. Example 2: Using list comprehension
num_of_lines = sum(1 for l in open('my_file.txt')) print(num_of_lines)
Output
3
- Open the file in read-only mode.
- Using a for loop, iterate through
open('my_file.txt')
. - After each iteration, return 1.
- Find the sum of the returned values.
Related posts:
Python Program to Find ASCII Value of Character
Python Artificial Intelligence Project for Beginners - Joshua Eckroth
Python dict()
Python input()
Python String rsplit()
Python Program to Check Armstrong Number
Python id()
Deep Learning in Python - LazyProgrammer
Python any()
Python Directory and Files Management
Python staticmethod()
Python Program to Create a Long Multiline String
Python Set update()
Python String rfind()
Python Program to Display the multiplication Table
Python hasattr()
Python Program to Multiply Two Matrices
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python abs()
Python Modules
Python type()
Python String swapcase()
Python Program to Print Colored Text to the Terminal
Python Machine Learning Second Edition - Sebastian Raschka & Vahid Mirjalili
Python Program to Check the File Size
Python Anonymous / Lambda Function
Python String rindex()
Deep Learning with Applications Using Python - Navin Kumar Manaswi
Python setattr()
Python RegEx
Python String endswith()
Python Program to Access Index of a List Using for Loop