从文件中读取行,且行偏移量为

问题描述

我想逐行读取文件,但是我想每两次读取时移动行指针。该文件看起来像

100
200
300
400

所以,如果我写

line_1 = f.readline()  # 100
line_2 = f.readline()  # 200

然后在第三个readline上,我将获得300。我想通过readline获得100,而我想通过一个增量语句获得200。然后将它们放入循环中,最后我要以这种方式获取代码行:

iteration #1: 100 and 200
iteration #2: 200 and 300
iteration #3: 300 and 400

我该怎么做?

解决方法

您可以创建一个生成器(它也会删除EOL字符,如果需要其他功能,您可以删除rstrip):

def readpairsoflines(f):
    l1 = f.readline().rstrip('\n')
    for l2 in f:
        l2 = l2.rstrip('\n')
        yield l1,l2
        l1 = l2

并像这样使用它:

with open(filename) as f:
    for l1,l2 in readpairsoflines(f):
        # Do something with your pair of lines,for example print them
        print(f'{l1} and {l2}')

结果:

100 and 200
200 and 300
300 and 400

使用这种方法,仅读取两行并将其保存在内存中。因此,它也适用于可能涉及内存的大文件。

,

我一直都很喜欢简单且可读的解决方案(尽管有时“ pythonic” 更少)。

with open("example.txt") as f:
    old = f.readline().rstrip()
    
    for line in f:
        line = line.rstrip()
        print("{} and  {}".format(old,line))
        old = line
  • 在遍历其余行之前执行第一次读取
  • 然后,打印所需的输出,并更新old字符串
  • 必须执行rstrip()调用才能删除不需要的尾随'\n'
  • 我认为如果文件少于两行,则无需打印任何内容;在特殊情况下,可以轻松修改代码以管理任何需求

输出:

100 and  200
200 and  300
300 and  400
,

现在,我建议像这样在换行符中拆分文档

with open('params.txt') as file:
    data = file.read()
data = data.split('\n')
for index,item in enumerate(data):
    try:
        print(str(item) + ' ' + str(data[index + 1]))
    except IndexError:
        print(str(item))

并使用一些列表逻辑打印您需要的内容 因此,此代码执行的操作是创建所需值的列表(对于大型文件而言效率不高)并获取其索引,因此在打印项目时,它还会打印列表中的下一个项目,并且对每个项目都执行索引错误,这是因为最后一项不会有下一项,但您也可以使用if else语句来解决它