本示例将使用 Python3 内置的函数实现统计文本文件的行数。提供了两个版本:
示例 1:一次性读取整个文件,代码简洁,适合普通大小的文本文件。代码如下:
def count_lines_small_file(file_path):
"""
统计小文件的行数
:param file_path: 文件路径(相对/绝对都可以)
:return: 总行数
"""
try:
# 打开文件,指定编码为 utf-8 避免中文乱码
with open(file_path, 'r', encoding='utf-8') as f:
# 读取所有行,返回列表
lines = f.readlines()
# 列表长度就是行数
return len(lines)
except FileNotFoundError:
return "错误:文件不存在"
except Exception as e:
return f"错误:{str(e)}"
# 调用示例
if __name__ == '__main__':
# 替换成你的文件路径
file = "test.txt"
result = count_lines_small_file(file)
print(f"文件总行数:{result}")运行结果:
文件总行数:4示例 2:逐行读取,不占用大量内存,适合 GB 级别的大文件,生产环境推荐用这个。代码如下:
def count_lines_large_file(file_path):
"""
统计大文件的行数(内存高效版)
:param file_path: 文件路径
:return: 总行数
"""
try:
line_count = 0
with open(file_path, 'r', encoding='utf-8') as f:
# 逐行遍历,只计数不存储
for _ in f:
line_count += 1
return line_count
except FileNotFoundError:
return "错误:文件不存在"
except Exception as e:
return f"错误:{str(e)}"
# 调用示例
if __name__ == '__main__':
# 替换成你的文件路径
file = "test.txt"
result = count_lines_large_file(file)
print(f"文件总行数:{result}")运行结果:
文件总行数:4