在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. 使用`len()`函数直接对文件对象操作(适用于文件较小的情况):
def count_lines(file_path):with open(file_path, 'r') as file:return len(file.readlines())file_path = 'example.txt'line_count = count_lines(file_path)print(f'文件 {file_path} 共有 {line_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_countfile_path = 'example.txt'line_count = count_lines(file_path)print(f'文件 {file_path} 共有 {line_count} 行。')
5. 使用`subprocess`模块调用系统命令`wc -l`(适用于不想用Python处理的情况):
import subprocessdef count_lines(file_path):result = subprocess.run(['wc', '-l', file_path], capture_output=True, text=True)return int(result.stdout.strip())file_path = 'example.txt'line_count = count_lines(file_path)print(f'文件 {file_path} 共有 {line_count} 行。')
请选择适合你需求的方法。
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 举报,一经查实,本站将立刻删除。
如需转载请保留出处:https://sigusoft.com/bj/43672.html