1. 使用`linecache`模块:
```python
import linecache
filename = "example.txt"
line_number = 5
line_content = linecache.getline(filename, line_number)
print(line_content)
2. 使用`readlines()`和下标:
```python
with open("example.txt", "r") as file:
lines = file.readlines()
print(lines[line_number - 1]) 注意下标从0开始
3. 使用`seek()`和`readline()`:
```python
with open("example.txt", "r") as file:
file.seek(line_number - 1) 注意下标从0开始
line_content = file.readline()
print(line_content)
4. 使用`itertools.islice()`:
```python
from itertools import islice
with open("example.txt", "r") as file:
for line in islice(file, line_number - 1, None): 注意下标从0开始
print(line)
5. 使用`enumerate()`和循环:
```python
with open("example.txt", "r") as file:
for line_number, line in enumerate(file, start=1): 注意下标从1开始
if line_number == line_number: 当line_number等于请求的行号时
print(line)
break
请选择适合您需求的方法来读取文件的指定行