如何使用 UliEngineering 在 Python 中统计文件行数
你可以使用 UliEngineering Python 库轻松统计文本文件的行数:
count_lines.py
from UliEngineering.Utils.Files import count_lines
import tempfile
import os
# 创建一个临时文件用于演示
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
# 统计行数
line_count = count_lines(temp_file)
print(f"File has {line_count} lines")
# 清理
os.unlink(temp_file)示例输出
count_lines_output.txt
File has 3 lines该函数高效地统计文本文件的行数。适用于快速按行确定文件大小,这在日志文件分析、数据处理和文本文件操作任务中很常见。该函数会自动处理 Unix 和 Windows 的行尾符。
相关文章
If this post helped you, please consider buying me a coffee or donating via PayPal to support research & publishing of new posts on TechOverflow