How to count lines in file in Python using UliEngineering
You can easily count the number of lines in a text file using the UliEngineering Python library:
count_lines.py
from UliEngineering.Utils.Files import count_lines
import tempfile
import os
# Create a temporary file for demonstration
with tempfile.NamedTemporaryFile(mode='w', delete=False, suffix='.txt') as f:
f.write("line 1\n")
f.write("line 2\n")
f.write("line 3\n")
temp_file = f.name
# Count lines
line_count = count_lines(temp_file)
print(f"File has {line_count} lines")
# Clean up
os.unlink(temp_file)Example output
count_lines_output.txt
File has 3 linesThis function efficiently counts the number of lines in a text file. It’s useful for quickly determining file size in terms of lines, which is common in log file analysis, data processing, and text file manipulation tasks. The function handles both Unix and Windows line endings automatically.
Related posts
- How to read text file in Python using UliEngineering
- How to write text file in Python using UliEngineering
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow