使用with open()读取文件,使用next(file)可以跳过一行

示例代码

def get_data_from_file(file_path, skip_line: int = 0):
    """从文件得到数据源"""
    # skip 为跳过的行数
    with open(file_path, 'r') as file:
        for i in range(skip_line):
            next(file)  # 跳过一行
        while True:
            line = file.readline()
            if not line:
                break  # 退出
            yield line


if __name__ == '__main__':
    for i in get_data_from_file("test.txt", skip_line=2):
        print(i)

其中test.txt文件内容如下:

hello1
world1
hello2
world2
hello3
world3
hello4
world4
hello5
world5
hello6
world6
hello7
world7
hello8
world8
hello9
world9

更多推荐

python读取文件,并指定跳过的行数