When working with files in Python, especially text files, one common task is to count the number of lines they contain. Whether you’re analyzing log files, processing datasets, or verifying data completeness, knowing the line count helps in structuring and optimizing your code.
Thankfully, Python provides multiple simple and efficient ways to count lines in a file—ranging from basic loops to powerful one-liners. In this blog, we’ll explore different methods to get accurate line counts with minimal code.
Why Count Lines in a File?
Counting lines in a file isn’t just a beginner’s exercise—it plays a crucial role in many real-world applications:
- 📊 Data Analysis: In large datasets (like CSVs or text corpora), counting lines helps you understand the dataset size before processing.
- 📝 Log Monitoring: For system logs or app logs, line counts can help track activity or detect missing data.
- ⏳ Progress Tracking: When reading and processing large files, knowing the total number of lines allows you to show progress bars or estimate processing time.
- 💾 Memory Management: Choosing the right approach to count lines ensures your program handles large files efficiently without consuming unnecessary memory.
Python Program to Count the Number of Lines in a File Using readline() Function
# Python Program to Count the Number of Lines in a File Using readline() Function #open the file to read with open(r"file.txt", 'r') as fp: # readlines() function to read all the lines at a single go lines = len(fp.readlines()) print('Total Number of lines:', lines)
Output:
Total Number of lines: 5
Python Program to Count the Number of Lines in a File Using enumerate
# Python Program to Count the Number of Lines in a File Using enumerate # open the file to read with open(r"file_one.txt", 'r') as fp: # enumerate() function adds a counter to an iterable and returns it in a format of enumerating objects for count, line in enumerate(fp): pass print('Total Number of lines:', count + 1)
Output:
Total Number of lines: 8
Python Program to Count the Number of Lines in a File Using counter
# Python Program to Count the Number of Lines in a File Using counter # Opening a file file = open("one.txt", "r") Counter = 0 # Reading from file Content = file.read() CoList = Content.split("\n") for i in CoList: if i: Counter += 1 print("This is the number of lines in the file") print(Counter)
Output:
This is the number of lines in the file
4
Python Program to Count the Number of Lines in a File Using sum() Function
# Python Program to Count the Number of Lines in a File Using sum() Function # Reading from file with open(r"file1.txt", 'r') as fp: lines = sum(1 for line in fp) print('Total Number of lines:', lines)
Output:
Total Number of lines: 6
Handling File Not Found or Errors
When working with file input/output, it’s essential to handle exceptions to prevent your program from crashing. Use a try-except
block to manage errors like missing files or permission issues.
✅ Example:
try: with open("data.txt", "r") as file: line_count = sum(1 for _ in file) print(f"Total lines: {line_count}") except FileNotFoundError: print("Error: The file was not found.") except PermissionError: print("Error: You do not have permission to read this file.") except Exception as e: print(f"An unexpected error occurred: {e}")
Real-World Scenario
Let’s say you’re working in IT or data analysis and need to count how many transactions are logged daily in a .csv
file. Using Python, you can quickly automate this task:
def count_lines(filename): try: with open(filename, 'r') as file: return sum(1 for _ in file) except FileNotFoundError: return "Log file not found." lines = count_lines("sales_log.csv") print(f"Total entries in today's log: {lines}")
This approach can also be applied to web server logs, error logs, or system-generated reports.
Interview Question or Mini Task
🧠 Task: Modify the line-counting code to count only non-empty lines (i.e., lines that are not just whitespace) or lines containing a specific keyword like “ERROR”.
Solution 1: Count Non-Empty Lines
with open("notes.txt", "r") as file: non_empty = sum(1 for line in file if line.strip()) print(f"Non-empty lines: {non_empty}")
Solution 2: Count Lines with a Specific Keyword
keyword = "ERROR" with open("log.txt", "r") as file: keyword_count = sum(1 for line in file if keyword in line) print(f"Lines with '{keyword}': {keyword_count}")
These variations are common in coding tests and real-world debugging scripts.
Conclusion
Counting lines in a file is a basic yet important task in many Python applications. Whether you use a for
loop, readlines()
, or a memory-efficient one-liner, Python gives you the flexibility to handle files your way. For large files, using sum(1 for _ in file)
inside a with open()
block is the best option for performance and memory use. Explore more Python tutorials and practical programming tips at Newtum – your go-to place for coding blogs, mini-projects, and structured learning courses.