温馨提示×

python怎么读取指定行数据

小亿
122
2023-11-20 23:45:13
栏目: 编程语言

要读取指定行的数据,可以使用以下方法:

  1. 使用 readlines() 方法将文件的所有行读取为一个列表;
  2. 使用列表索引来访问指定行的数据。

以下是一个示例代码:

def read_specific_line(file_path, line_number):
    with open(file_path, 'r') as file:
        lines = file.readlines()
        if line_number <= len(lines):
            return lines[line_number - 1]
        else:
            return '指定行不存在'

file_path = 'example.txt'  # 文件路径
line_number = 3  # 指定的行号
line = read_specific_line(file_path, line_number)
print(line)

在上述代码中,read_specific_line() 函数接受文件路径和行号作为参数。它首先使用 open() 函数打开文件,并使用 readlines() 方法将文件的所有行读取为一个列表。然后,它通过索引 line_number - 1 来访问指定行的数据,并将其返回。

注意:行号是从 1 开始计数的,所以在访问列表时需要将行号减去 1。如果指定的行号超过了文件的行数,函数将返回 '指定行不存在'

0