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 for Programmers with introductory AI case studies - Paul Deitel & Harvey Deitel
Python list()
Python Set isdisjoint()
Python Machine Learning Eqution Reference - Sebastian Raschka
Python Set issubset()
Python String isidentifier()
Python Program to Copy a File
Python callable()
Python String isalpha()
Python List insert()
Python String isalnum()
Python String splitlines()
Python Program to Print Hello world!
How to get current date and time in Python?
Python String partition()
Python Program to Make a Flattened List from Nested List
Python Program to Sort a Dictionary by Value
Python repr()
Python Program to Convert Decimal to Binary Using Recursion
Python Global Keyword
Python String title()
Python Deeper Insights into Machine Learning - Sebastian Raschka & David Julian & John Hearty
Python Program to Get the Full Path of the Current Working Directory
Python Program to Check If Two Strings are Anagram
Python Program to Find the Sum of Natural Numbers
Python Statement, Indentation and Comments
Python Program to Iterate Through Two Lists in Parallel
Python open()
Python Set clear()
Python frozenset()
Python Machine Learning Cookbook - Practical solutions from preprocessing to Deep Learning - Chris A...
Applied Text Analysis with Python - Benjamin Benfort & Rebecca Bibro & Tony Ojeda