π Day 87/150 – Count Lines in a File in Python
Counting the number of lines in a file is a common task in Python. It's useful for analyzing text files, processing datasets, validating file contents, and working with logs. Python provides several simple ways to count lines efficiently.
In this post, we'll explore four different methods to count the lines in a file.
Method 1 – Using a for Loop
Read the file line by line and increment a counter.
count = 0 with open("sample.txt", "r") as file: for line in file: count += 1 print("Total lines:", count)
Output
Total lines: 3
Explanation:
- Initialize a counter with 0.
- Iterate through each line in the file.
- Increase the counter for every line.
Method 2 – Using readlines()
The readlines() method reads all lines into a list. The length of the list gives the total number of lines.
Total lines: 3with open("sample.txt", "r") as file: lines = file.readlines() print("Total lines:", len(lines))
Output
Explanation:
- readlines() returns a list of all lines.
- len() counts the number of elements in the list.
Method 3 – Using sum()
A concise and memory-efficient approach.
Total lines: 3with open("sample.txt", "r") as file: count = sum(1 for line in file) print("Total lines:", count)
Output
Explanation:
- The generator expression produces 1 for each line.
- sum() adds them together to get the total count.
Method 4 – Taking File Name from User
Allow the user to specify which file to count.
filename = input("Enter file name: ") with open(filename, "r") as file: count = sum(1 for line in file) print("Total lines:", count)
Sample Input
Total lines: 3sample.txt
Output
Explanation:
- Accepts a file name from the user.
- Counts the number of lines dynamically.
Comparison of Methods
| Method | Best For |
|---|---|
| for Loop | Understanding the counting logic |
| readlines() | Small files |
| sum() | Fast and memory-efficient |
| User Input | Interactive programs |
π₯ Key Takeaways
- A for loop is the easiest way to understand how line counting works.
- readlines() is suitable for small files but loads the entire file into memory.
- sum(1 for line in file) is a clean and efficient way to count lines.
- Always use the with statement to ensure files are closed automatically.
- Counting lines is useful for file analysis, log processing, and data validation.


0 Comments:
Post a Comment