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:
Machine Learning Applications Using Python - Cases studies form Healthcare, Retail, and Finance - Pu...
Python Set symmetric_difference_update()
Python Program to Iterate Through Two Lists in Parallel
Python String split()
Python String join()
Python slice()
Python Closures
Python Program to Print all Prime Numbers in an Interval
Python sorted()
Python Program to Find LCM
Python Program to Safely Create a Nested Directory
Python sleep()
Python hash()
Python exec()
Python strftime()
Python Data Types
Python Program to Shuffle Deck of Cards
Python min()
Python Object Oriented Programming
Python setattr()
Python Program to Delete an Element From a Dictionary
Python Dictionary setdefault()
Python Program to Find Hash of File
Python ord()
Python Program to Randomly Select an Element From the List
Python hex()
Deep Learning with Python - A Hands-on Introduction - Nikhil Ketkar
Python list()
Python String islower()
Python String upper()
Python Program to Parse a String to a Float or Int
Python Program to Check If Two Strings are Anagram