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 a Substring of a String
Python List index()
Python chr()
Python String title()
Python Program to Convert Decimal to Binary Using Recursion
Python Program to Display the multiplication Table
Python Program to Multiply Two Matrices
Java – Write an InputStream to a File
Python Dictionary get()
Python String rfind()
Python Program to Remove Duplicate Element From a List
Python Program to Create a Countdown Timer
Python String count()
Python Data Analytics with Pandas, NumPy and Matplotlib - Fabio Nelli
Python Deep Learning - Valentino Zocca & Gianmario Spacagna & Daniel Slater & Peter Roelants
Python Program to Differentiate Between del, remove, and pop on a List
Python String lower()
Python Set clear()
Python open()
Building Machine Learning Systems with Python - Willi Richert & Luis Pedro Coelho
Python Object Oriented Programming
Python getattr()
Python Program to Make a Flattened List from Nested List
Python bool()
Python exec()
Python *args and **kwargs
Python Operators
Machine Learning with Python for everyone - Mark E.Fenner
Python zip()
Debug a JavaMail Program
Python Functions
Python Program to Swap Two Variables