Python 统计text 的行数
时间: 2024-12-19 19:06:31 浏览: 9
在Python中,统计文本文件的行数有多种方法。以下是几种常用的方法:
1. 使用内置函数 `open()` 和 `readlines()`:
```python
def count_lines(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
lines = file.readlines()
return len(lines)
# 使用示例
file_path = 'example.txt'
line_count = count_lines(file_path)
print(f'The file has {line_count} lines.')
```
2. 使用 `for` 循环逐行读取:
```python
def count_lines(file_path):
line_count = 0
with open(file_path, 'r', encoding='utf-8') as file:
for line in file:
line_count += 1
return line_count
# 使用示例
file_path = 'example.txt'
line_count = count_lines(file_path)
print(f'The file has {line_count} lines.')
```
3. 使用生成器表达式:
```python
def count_lines(file_path):
with open(file_path, 'r', encoding='utf-8') as file:
return sum(1 for line in file)
# 使用示例
file_path = 'example.txt'
line_count = count_lines(file_path)
print(f'The file has {line_count} lines.')
```
这些方法都能有效地统计文本文件的行数。选择哪种方法取决于你的具体需求和个人偏好。
阅读全文