1. 使用`readlines()`方法:
```python
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()`函数:```pythondef count_lines(file_path):
line_count = 0
with open(file_path, 'r') as file:
for line in file:
line_count += 1
return line_count
file_path = 'example.txt'
line_count = count_lines(file_path)
print(f'文件 {file_path} 共有 {line_count} 行。')
3. 使用`len()`函数直接对文件对象操作(适用于文件较小的情况):
```python
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`循环逐行读取文件(适用于大文件,节省内存):```pythondef count_lines(file_path):
line_count = 0
with open(file_path, 'r') as file:
for line in file:
line_count += 1
return line_count
file_path = 'example.txt'
line_count = count_lines(file_path)
print(f'文件 {file_path} 共有 {line_count} 行。')
5. 使用`subprocess`模块调用系统命令`wc -l`(适用于不想用Python处理的情况):
```python
import subprocess
def 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} 行。')
请选择适合你需求的方法。
