在Python中,计算文件行数可以通过以下几种方法实现:
1. 使用`readlines()`方法:
def count_lines(file_path):with open(file_path, 'r') as file:lines = file.readlines()return len(lines)
2. 使用`enumerate()`函数:
def count_lines(file_path):line_count = 0with open(file_path, 'r') as file:for line in file:line_count += 1return line_count
3. 通过统计换行符“\n”的数量来计算行数:

def count_lines(file_path):count = 0with open(file_path, 'rb') as file:buffer = file.read(8192*1024)while buffer:count += buffer.count(b'\n')buffer = file.read(8192*1024)return count
4. 使用`for`循环逐行读取文件内容:
def count_lines(file_path):line_count = 0with open(file_path, 'r') as file:for line in file:line_count += 1return line_count
以上方法各有优缺点,对于小文件,使用`readlines()`或`enumerate()`方法比较简单快捷;而对于大文件,使用统计换行符数量的方法可能更为高效,因为它不需要一次性将整个文件加载到内存中。
