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 Get the Class Name of an Instance
Python Program to Measure the Elapsed Time in Python
Python hash()
Python Set difference_update()
Python Shallow Copy and Deep Copy
Python complex()
Python String partition()
How to Get Started With Python?
Python String islower()
Python Numbers, Type Conversion and Mathematics
Python Set add()
Python Matrices and NumPy Arrays
Python Program to Iterate Over Dictionaries Using for Loop
Python Dictionary copy()
Python Program to Create a Countdown Timer
Check If a File or Directory Exists in Java
Python Program to Find the Factors of a Number
Python globals()
Python Global, Local and Nonlocal variables
Python filter()
Python Set update()
Python String translate()
Python Program to Convert Bytes to a String
Python strptime()
Python Program to Display Powers of 2 Using Anonymous Function
Node.js vs Python for Backend Development
Python list()
Python String startswith()
Python String lstrip()
Natural Language Processing with Python - Steven Bird & Ewan Klein & Edward Loper
Python String capitalize()
Python Program to Iterate Through Two Lists in Parallel