在Python中,计算文档(文件)的行数可以通过以下几种方法实现:
1. 使用`readlines()`方法:
def count_lines(file_path):with open(file_path, 'r') as file:lines = file.readlines()return len(lines)file_path = 'example.txt' 替换为实际文件路径line_count = count_lines(file_path)print(f'文件 {file_path} 共有 {line_count} 行。')
2. 使用`enumerate()`函数:
def count_lines(file_path):line_count = 0with open(file_path, 'r') as file:for line in file:line_count += 1return line_countfile_path = 'example.txt' 替换为实际文件路径line_count = count_lines(file_path)print(f'文件 {file_path} 共有 {line_count} 行。')

3. 使用`for`循环逐行读取:
def count_lines(file_path):line_count = 0with open(file_path, 'r') as file:for _ in file:line_count += 1return line_countfile_path = 'example.txt' 替换为实际文件路径line_count = count_lines(file_path)print(f'文件 {file_path} 共有 {line_count} 行。')
4. 对于非常大的文件,可以使用以下方法来提高效率,通过读取文件的一部分内容并统计换行符的数量:
def count_lines(file_path):count = 0with open(file_path, 'rb') as file:buffer = file.read(8192 * 1024) 读取8MB的块while buffer:count += buffer.count(b'\n') 统计换行符的数量buffer = file.read(8192 * 1024) 继续读取下一块return countfile_path = 'example.txt' 替换为实际文件路径line_count = count_lines(file_path)print(f'文件 {file_path} 共有 {line_count} 行。')
以上方法均可用于计算文档的行数。选择哪一种方法取决于文件的大小以及你对性能的要求
