枚举 Python 中的行时如何获取 index + 1 的行

How can I get the line of index + 1 when enumerating lines in Python

我正在使用代码 for index, line in enumerate(lines): 逐行阅读文件。我可以使用 (line).

访问当前行的字符串

是否可以访问下一行向前看?我曾尝试使用 next_line = line(index + 1) 访问它,但这会造成错误。

代码

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            next_line = line(index + 1)
            print(f'Index is {index + 1}')
            # Do something here

您可以像往常一样从列表中访问它,这将导致最后一次迭代出现异常,因此我添加了一个检查来防止这种情况发生:

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            if index < len(lines) - 1:
                next_line = lines[index+1]
                print(f'Index is {index + 1}')
                # Do something here

line 是一个字符串,因此您无法执行所需的操作。 尝试这样的事情:

with open(sys.argv[1]) as f1:
    with open(sys.argv[2], 'a') as f2:
        lines = f1.readlines()
        prev_line = ""
        string_length = 60
        for index, line in enumerate(lines):
            try:
                next_line = lines[index + 1]
            except IndexError:
                pass
            print(f'Index is {index + 1}')
            # Do something here