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 Artificial Intelligence Project for Beginners - Joshua Eckroth
Machine Learning Mastery with Python - Understand your data, create accurate models and work project...
Python Data Structures and Algorithms - Benjamin Baka
Python Program to Get the Full Path of the Current Working Directory
Python Dictionary pop()
Python Program to Count the Number of Digits Present In a Number
Python Program to Find Factorial of Number Using Recursion
Python String startswith()
Python Set difference_update()
Python Program to Convert String to Datetime
Python tuple()
APIs in Node.js vs Python - A Comparison
Python issubclass()
Python Tuple
Python Program to Count the Occurrence of an Item in a List
Python String upper()
Python Set add()
Python Program to Find Armstrong Number in an Interval
Intelligent Projects Using Python - Santanu Pattanayak
Python List append()
Python bin()
Python Program to Check the File Size
How to Get Started With Python?
Python divmod()
Python isinstance()
Python Multiple Inheritance
Python Machine Learning Third Edition - Sebastian Raschka & Vahid Mirjalili
Python List clear()
Python compile()
Python Program to Print Colored Text to the Terminal
Python Program to Print Hello world!
File Upload with Spring MVC