python中如何读取文件中指定行数
时间: 2023-09-26 09:09:56 浏览: 113
在 Python 中,可以使用以下方式读取文件中的指定行数:
```python
def read_specific_lines(file_path, line_numbers):
with open(file_path, 'r') as file:
lines = file.readlines()
for line_number in line_numbers:
if line_number <= len(lines):
print(lines[line_number - 1])
else:
print(f"Line number {line_number} is out of range.")
# 示例使用
file_path = 'path/to/your/file.txt'
line_numbers = [2, 5, 8] # 想要读取的行数
read_specific_lines(file_path, line_numbers)
```
在上面的代码中,`read_specific_lines` 函数接受文件路径 `file_path` 和要读取的行号列表 `line_numbers`。首先,它使用 `open` 函数打开文件,并使用 `readlines` 方法读取所有行并存储在 `lines` 列表中。
然后,它遍历给定的行号列表,检查行号是否在有效的行范围内。如果是,它将打印出对应行号的内容。如果不在有效范围内,它将打印出相应的错误消息。
注意:行号从 1 开始,而列表的索引从 0 开始,所以需要将行号减去 1 来获取正确的索引位置。